target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
src/DropDownItem.js
loktar00/react-custom-dropdown
import React, {Component, PropTypes} from 'react'; import Radium from 'radium'; let styles = { menuItem: { cursor: 'pointer', fontSize: '13px', padding: '6px 0 6px 20px', ':hover' : { backgroundColor: '#52a6fa', color: '#fff' } } }; @Radium export default class DropDownItem extends Component { static displayName = 'DropDownItem'; static propTypes = { onClick: PropTypes.func, style: PropTypes.oneOfType([ PropTypes.array, PropTypes.object ]) }; static defaultProps = { onClick: function(){} }; constructor(props) { super(props); } render() { return ( <div onClick={::this.handleClick} style={[styles.menuItem, this.props.style]}>{this.props.children}</div> ); } handleClick(evt) { this.props.onClick(evt); } }
packages/cf-component-card/src/CardContent.js
mdno/mdno.github.io
import React from 'react'; import PropTypes from 'prop-types'; class CardContent extends React.Component { render() { return ( <div className="cf-card__content"> <h3 className="cf-card__title"> {this.props.title} </h3> {this.props.children} {this.props.footerMessage ? <div className="cf-card__footer_message"> {this.props.footerMessage} </div> : null} </div> ); } } CardContent.propTypes = { title: PropTypes.node, footerMessage: PropTypes.string, children: PropTypes.node }; export default CardContent;
src/svg-icons/image/filter-9-plus.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter9Plus = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm11 7V8c0-1.11-.9-2-2-2h-1c-1.1 0-2 .89-2 2v1c0 1.11.9 2 2 2h1v1H9v2h3c1.1 0 2-.89 2-2zm-3-3V8h1v1h-1zm10-8H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 8h-2V7h-2v2h-2v2h2v2h2v-2h2v6H7V3h14v6z"/> </SvgIcon> ); ImageFilter9Plus = pure(ImageFilter9Plus); ImageFilter9Plus.displayName = 'ImageFilter9Plus'; ImageFilter9Plus.muiName = 'SvgIcon'; export default ImageFilter9Plus;
frontend/src/Settings/Profiles/Quality/QualityProfileItemDragSource.js
geogolem/Radarr
import classNames from 'classnames'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { DragSource, DropTarget } from 'react-dnd'; import { findDOMNode } from 'react-dom'; import { QUALITY_PROFILE_ITEM } from 'Helpers/dragTypes'; import QualityProfileItem from './QualityProfileItem'; import QualityProfileItemGroup from './QualityProfileItemGroup'; import styles from './QualityProfileItemDragSource.css'; const qualityProfileItemDragSource = { beginDrag(props) { const { editGroups, qualityIndex, groupId, qualityId, name, allowed } = props; return { editGroups, qualityIndex, groupId, qualityId, isGroup: !qualityId, name, allowed }; }, endDrag(props, monitor, component) { props.onQualityProfileItemDragEnd(monitor.didDrop()); } }; const qualityProfileItemDropTarget = { hover(props, monitor, component) { const { qualityIndex: dragQualityIndex, isGroup: isDragGroup } = monitor.getItem(); const dropQualityIndex = props.qualityIndex; const isDropGroupItem = !!(props.qualityId && props.groupId); // Use childNodeIndex to select the correct node to get the middle of so // we don't bounce between above and below causing rapid setState calls. const childNodeIndex = component.props.isOverCurrent && component.props.isDraggingUp ? 1 :0; const componentDOMNode = findDOMNode(component).children[childNodeIndex]; const hoverBoundingRect = componentDOMNode.getBoundingClientRect(); const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; const clientOffset = monitor.getClientOffset(); const hoverClientY = clientOffset.y - hoverBoundingRect.top; // If we're hovering over a child don't trigger on the parent if (!monitor.isOver({ shallow: true })) { return; } // Don't show targets for dropping on self if (dragQualityIndex === dropQualityIndex) { return; } // Don't allow a group to be dropped inside a group if (isDragGroup && isDropGroupItem) { return; } let dropPosition = null; // Determine drop position based on position over target if (hoverClientY > hoverMiddleY) { dropPosition = 'below'; } else if (hoverClientY < hoverMiddleY) { dropPosition = 'above'; } else { return; } props.onQualityProfileItemDragMove({ dragQualityIndex, dropQualityIndex, dropPosition }); } }; function collectDragSource(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() }; } function collectDropTarget(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), isOverCurrent: monitor.isOver({ shallow: true }) }; } class QualityProfileItemDragSource extends Component { // // Render render() { const { editGroups, groupId, qualityId, name, allowed, items, qualityIndex, isDragging, isDraggingUp, isDraggingDown, isOverCurrent, connectDragSource, connectDropTarget, onCreateGroupPress, onDeleteGroupPress, onQualityProfileItemAllowedChange, onItemGroupAllowedChange, onItemGroupNameChange, onQualityProfileItemDragMove, onQualityProfileItemDragEnd } = this.props; const isBefore = !isDragging && isDraggingUp && isOverCurrent; const isAfter = !isDragging && isDraggingDown && isOverCurrent; return connectDropTarget( <div className={classNames( styles.qualityProfileItemDragSource, isBefore && styles.isDraggingUp, isAfter && styles.isDraggingDown )} > { isBefore && <div className={classNames( styles.qualityProfileItemPlaceholder, styles.qualityProfileItemPlaceholderBefore )} /> } { !!groupId && qualityId == null && <QualityProfileItemGroup editGroups={editGroups} groupId={groupId} name={name} allowed={allowed} items={items} qualityIndex={qualityIndex} isDragging={isDragging} isDraggingUp={isDraggingUp} isDraggingDown={isDraggingDown} connectDragSource={connectDragSource} onDeleteGroupPress={onDeleteGroupPress} onQualityProfileItemAllowedChange={onQualityProfileItemAllowedChange} onItemGroupAllowedChange={onItemGroupAllowedChange} onItemGroupNameChange={onItemGroupNameChange} onQualityProfileItemDragMove={onQualityProfileItemDragMove} onQualityProfileItemDragEnd={onQualityProfileItemDragEnd} /> } { qualityId != null && <QualityProfileItem editGroups={editGroups} groupId={groupId} qualityId={qualityId} name={name} allowed={allowed} qualityIndex={qualityIndex} isDragging={isDragging} isOverCurrent={isOverCurrent} connectDragSource={connectDragSource} onCreateGroupPress={onCreateGroupPress} onQualityProfileItemAllowedChange={onQualityProfileItemAllowedChange} /> } { isAfter && <div className={classNames( styles.qualityProfileItemPlaceholder, styles.qualityProfileItemPlaceholderAfter )} /> } </div> ); } } QualityProfileItemDragSource.propTypes = { editGroups: PropTypes.bool.isRequired, groupId: PropTypes.number, qualityId: PropTypes.number, name: PropTypes.string.isRequired, allowed: PropTypes.bool.isRequired, items: PropTypes.arrayOf(PropTypes.object), qualityIndex: PropTypes.string.isRequired, isDragging: PropTypes.bool, isDraggingUp: PropTypes.bool, isDraggingDown: PropTypes.bool, isOverCurrent: PropTypes.bool, isInGroup: PropTypes.bool, connectDragSource: PropTypes.func, connectDropTarget: PropTypes.func, onCreateGroupPress: PropTypes.func, onDeleteGroupPress: PropTypes.func, onQualityProfileItemAllowedChange: PropTypes.func.isRequired, onItemGroupAllowedChange: PropTypes.func, onItemGroupNameChange: PropTypes.func, onQualityProfileItemDragMove: PropTypes.func.isRequired, onQualityProfileItemDragEnd: PropTypes.func.isRequired }; export default DropTarget( QUALITY_PROFILE_ITEM, qualityProfileItemDropTarget, collectDropTarget )(DragSource( QUALITY_PROFILE_ITEM, qualityProfileItemDragSource, collectDragSource )(QualityProfileItemDragSource));
ajax/libs/react-bootstrap-table/2.5.4/react-bootstrap-table.js
seogi1004/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactBootstrapTable"] = factory(require("react"), require("react-dom")); else root["ReactBootstrapTable"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_6__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _BootstrapTable = __webpack_require__(1); var _BootstrapTable2 = _interopRequireDefault(_BootstrapTable); var _TableHeaderColumn = __webpack_require__(44); var _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn); if (typeof window !== 'undefined') { window.BootstrapTable = _BootstrapTable2['default']; window.TableHeaderColumn = _TableHeaderColumn2['default']; } exports.BootstrapTable = _BootstrapTable2['default']; exports.TableHeaderColumn = _TableHeaderColumn2['default']; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* eslint no-alert: 0 */ /* eslint max-len: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _TableHeader = __webpack_require__(5); var _TableHeader2 = _interopRequireDefault(_TableHeader); var _TableBody = __webpack_require__(8); var _TableBody2 = _interopRequireDefault(_TableBody); var _paginationPaginationList = __webpack_require__(32); var _paginationPaginationList2 = _interopRequireDefault(_paginationPaginationList); var _toolbarToolBar = __webpack_require__(34); var _toolbarToolBar2 = _interopRequireDefault(_toolbarToolBar); var _TableFilter = __webpack_require__(35); var _TableFilter2 = _interopRequireDefault(_TableFilter); var _storeTableDataStore = __webpack_require__(36); var _util = __webpack_require__(37); var _util2 = _interopRequireDefault(_util); var _csv_export_util = __webpack_require__(38); var _csv_export_util2 = _interopRequireDefault(_csv_export_util); var _Filter = __webpack_require__(42); var BootstrapTable = (function (_Component) { _inherits(BootstrapTable, _Component); function BootstrapTable(props) { var _this = this; _classCallCheck(this, BootstrapTable); _get(Object.getPrototypeOf(BootstrapTable.prototype), 'constructor', this).call(this, props); this.handleSort = function (order, sortField) { if (_this.props.options.onSortChange) { _this.props.options.onSortChange(sortField, order, _this.props); } if (_this.isRemoteDataSource()) { _this.store.setSortInfo(order, sortField); return; } var result = _this.store.sort(order, sortField).get(); _this.setState({ data: result }); }; this.handlePaginationData = function (page, sizePerPage) { var _props$options = _this.props.options; var onPageChange = _props$options.onPageChange; var pageStartIndex = _props$options.pageStartIndex; if (onPageChange) { onPageChange(page, sizePerPage); } _this.setState({ currPage: page, sizePerPage: sizePerPage }); if (_this.isRemoteDataSource()) { return; } // We calculate an offset here in order to properly fetch the indexed data, // despite the page start index not always being 1 var normalizedPage = undefined; if (pageStartIndex !== undefined) { var offset = Math.abs(_Const2['default'].PAGE_START_INDEX - pageStartIndex); normalizedPage = page + offset; } else { normalizedPage = page; } var result = _this.store.page(normalizedPage, sizePerPage).get(); _this.setState({ data: result }); }; this.handleMouseLeave = function () { if (_this.props.options.onMouseLeave) { _this.props.options.onMouseLeave(); } }; this.handleMouseEnter = function () { if (_this.props.options.onMouseEnter) { _this.props.options.onMouseEnter(); } }; this.handleRowMouseOut = function (row, event) { if (_this.props.options.onRowMouseOut) { _this.props.options.onRowMouseOut(row, event); } }; this.handleRowMouseOver = function (row, event) { if (_this.props.options.onRowMouseOver) { _this.props.options.onRowMouseOver(row, event); } }; this.handleRowClick = function (row) { if (_this.props.options.onRowClick) { _this.props.options.onRowClick(row); } }; this.handleSelectAllRow = function (e) { var isSelected = e.currentTarget.checked; var keyField = _this.store.getKeyField(); var _props$selectRow = _this.props.selectRow; var onSelectAll = _props$selectRow.onSelectAll; var unselectable = _props$selectRow.unselectable; var selected = _props$selectRow.selected; var selectedRowKeys = []; var result = true; var rows = isSelected ? _this.store.get() : _this.store.getRowByKey(_this.state.selectedRowKeys); if (unselectable && unselectable.length > 0) { if (isSelected) { rows = rows.filter(function (r) { return unselectable.indexOf(r[keyField]) === -1 || selected && selected.indexOf(r[keyField]) !== -1; }); } else { rows = rows.filter(function (r) { return unselectable.indexOf(r[keyField]) === -1; }); } } if (onSelectAll) { result = _this.props.selectRow.onSelectAll(isSelected, rows); } if (typeof result == 'undefined' || result !== false) { if (isSelected) { selectedRowKeys = Array.isArray(result) ? result : rows.map(function (r) { return r[keyField]; }); } else { if (unselectable && selected) { selectedRowKeys = selected.filter(function (r) { return unselectable.indexOf(r) > -1; }); } } _this.store.setSelectedRowKey(selectedRowKeys); _this.setState({ selectedRowKeys: selectedRowKeys }); } }; this.handleShowOnlySelected = function () { _this.store.ignoreNonSelected(); var result = undefined; if (_this.props.pagination) { result = _this.store.page(1, _this.state.sizePerPage).get(); } else { result = _this.store.get(); } _this.setState({ data: result, currPage: _this.props.options.pageStartIndex || _Const2['default'].PAGE_START_INDEX }); }; this.handleSelectRow = function (row, isSelected, e) { var result = true; var currSelected = _this.store.getSelectedRowKeys(); var rowKey = row[_this.store.getKeyField()]; var selectRow = _this.props.selectRow; if (selectRow.onSelect) { result = selectRow.onSelect(row, isSelected, e); } if (typeof result === 'undefined' || result !== false) { if (selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) { currSelected = isSelected ? [rowKey] : []; } else { if (isSelected) { currSelected.push(rowKey); } else { currSelected = currSelected.filter(function (key) { return rowKey !== key; }); } } _this.store.setSelectedRowKey(currSelected); _this.setState({ selectedRowKeys: currSelected }); } }; this.handleAddRow = function (newObj) { var onAddRow = _this.props.options.onAddRow; if (onAddRow) { var colInfos = _this.store.getColInfos(); onAddRow(newObj, colInfos); } if (_this.isRemoteDataSource()) { if (_this.props.options.afterInsertRow) { _this.props.options.afterInsertRow(newObj); } return null; } try { _this.store.add(newObj); } catch (e) { return e; } _this._handleAfterAddingRow(newObj); }; this.getPageByRowKey = function (rowKey) { var sizePerPage = _this.state.sizePerPage; var currentData = _this.store.getCurrentDisplayData(); var keyField = _this.store.getKeyField(); var result = currentData.findIndex(function (x) { return x[keyField] === rowKey; }); if (result > -1) { return parseInt(result / sizePerPage, 10) + 1; } else { return result; } }; this.handleDropRow = function (rowKeys) { var dropRowKeys = rowKeys ? rowKeys : _this.store.getSelectedRowKeys(); // add confirm before the delete action if that option is set. if (dropRowKeys && dropRowKeys.length > 0) { if (_this.props.options.handleConfirmDeleteRow) { _this.props.options.handleConfirmDeleteRow(function () { _this.deleteRow(dropRowKeys); }, dropRowKeys); } else if (confirm('Are you sure you want to delete?')) { _this.deleteRow(dropRowKeys); } } }; this.handleFilterData = function (filterObj) { var onFilterChange = _this.props.options.onFilterChange; if (onFilterChange) { var colInfos = _this.store.getColInfos(); onFilterChange(filterObj, colInfos); } _this.setState({ currPage: _this.props.options.pageStartIndex || _Const2['default'].PAGE_START_INDEX }); if (_this.isRemoteDataSource()) { if (_this.props.options.afterColumnFilter) { _this.props.options.afterColumnFilter(filterObj, _this.store.getDataIgnoringPagination()); } return; } _this.store.filter(filterObj); var sortObj = _this.store.getSortInfo(); if (sortObj) { _this.store.sort(sortObj.order, sortObj.sortField); } var result = undefined; if (_this.props.pagination) { var sizePerPage = _this.state.sizePerPage; result = _this.store.page(1, sizePerPage).get(); } else { result = _this.store.get(); } if (_this.props.options.afterColumnFilter) { _this.props.options.afterColumnFilter(filterObj, _this.store.getDataIgnoringPagination()); } _this.setState({ data: result }); }; this.handleExportCSV = function () { var result = {}; var csvFileName = _this.props.csvFileName; var onExportToCSV = _this.props.options.onExportToCSV; if (onExportToCSV) { result = onExportToCSV(); } else { result = _this.store.getDataIgnoringPagination(); } var keys = []; _this.props.children.map(function (column) { if (column.props['export'] === true || typeof column.props['export'] === 'undefined' && column.props.hidden === false) { keys.push({ field: column.props.dataField, format: column.props.csvFormat, header: column.props.csvHeader || column.props.dataField }); } }); if (typeof csvFileName === 'function') { csvFileName = csvFileName(); } (0, _csv_export_util2['default'])(result, keys, csvFileName); }; this.handleSearch = function (searchText) { var onSearchChange = _this.props.options.onSearchChange; if (onSearchChange) { var colInfos = _this.store.getColInfos(); onSearchChange(searchText, colInfos, _this.props.multiColumnSearch); } _this.setState({ currPage: _this.props.options.pageStartIndex || _Const2['default'].PAGE_START_INDEX }); if (_this.isRemoteDataSource()) { if (_this.props.options.afterSearch) { _this.props.options.afterSearch(searchText, _this.store.getDataIgnoringPagination()); } return; } _this.store.search(searchText); var sortObj = _this.store.getSortInfo(); if (sortObj) { _this.store.sort(sortObj.order, sortObj.sortField); } var result = undefined; if (_this.props.pagination) { var sizePerPage = _this.state.sizePerPage; result = _this.store.page(1, sizePerPage).get(); } else { result = _this.store.get(); } if (_this.props.options.afterSearch) { _this.props.options.afterSearch(searchText, _this.store.getDataIgnoringPagination()); } _this.setState({ data: result }); }; this._scrollHeader = function (e) { _this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft; }; this._adjustTable = function () { _this._adjustHeaderWidth(); _this._adjustHeight(); }; this._adjustHeaderWidth = function () { var header = _this.refs.header.refs.header; var headerContainer = _this.refs.header.refs.container; var tbody = _this.refs.body.refs.tbody; var firstRow = tbody.childNodes[0]; var isScroll = headerContainer.offsetWidth !== tbody.parentNode.offsetWidth; var scrollBarWidth = isScroll ? _util2['default'].getScrollBarWidth() : 0; if (firstRow && _this.store.getDataNum()) { var cells = firstRow.childNodes; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; var computedStyle = getComputedStyle(cell); var width = parseFloat(computedStyle.width.replace('px', '')); if (_this.isIE) { var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace('px', '')); var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace('px', '')); var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace('px', '')); var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace('px', '')); width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth; } var lastPadding = cells.length - 1 === i ? scrollBarWidth : 0; if (width <= 0) { width = 120; cell.width = width + lastPadding + 'px'; } var result = width + lastPadding + 'px'; header.childNodes[i].style.width = result; header.childNodes[i].style.minWidth = result; } } else { _react2['default'].Children.forEach(_this.props.children, function (child, i) { if (child.props.width) { header.childNodes[i].style.width = child.props.width + 'px'; header.childNodes[i].style.minWidth = child.props.width + 'px'; } }); } }; this._adjustHeight = function () { var height = _this.props.height; var maxHeight = _this.props.maxHeight; if (typeof height === 'number' && !isNaN(height) || height.indexOf('%') === -1) { _this.refs.body.refs.container.style.height = parseFloat(height, 10) - _this.refs.header.refs.container.offsetHeight + 'px'; } if (maxHeight) { maxHeight = typeof maxHeight === 'number' ? maxHeight : parseInt(maxHeight.replace('px', ''), 10); _this.refs.body.refs.container.style.maxHeight = maxHeight - _this.refs.header.refs.container.offsetHeight + 'px'; } }; this.isIE = false; this._attachCellEditFunc(); if (_util2['default'].canUseDOM()) { this.isIE = document.documentMode; } this.store = new _storeTableDataStore.TableDataStore(this.props.data.slice()); this.initTable(this.props); if (this.filter) { this.filter.on('onFilterChange', function (currentFilter) { _this.handleFilterData(currentFilter); }); } if (this.props.selectRow && this.props.selectRow.selected) { var copy = this.props.selectRow.selected.slice(); this.store.setSelectedRowKey(copy); } var currPage = _Const2['default'].PAGE_START_INDEX; if (typeof this.props.options.page !== 'undefined') { currPage = this.props.options.page; } else if (typeof this.props.options.pageStartIndex !== 'undefined') { currPage = this.props.options.pageStartIndex; } this.state = { data: this.getTableData(), currPage: currPage, sizePerPage: this.props.options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0], selectedRowKeys: this.store.getSelectedRowKeys() }; } _createClass(BootstrapTable, [{ key: 'initTable', value: function initTable(props) { var _this2 = this; var keyField = props.keyField; var isKeyFieldDefined = typeof keyField === 'string' && keyField.length; _react2['default'].Children.forEach(props.children, function (column) { if (column.props.isKey) { if (keyField) { throw 'Error. Multiple key column be detected in TableHeaderColumn.'; } keyField = column.props.dataField; } if (column.props.filter) { // a column contains a filter if (!_this2.filter) { // first time create the filter on the BootstrapTable _this2.filter = new _Filter.Filter(); } // pass the filter to column with filter column.props.filter.emitter = _this2.filter; } }); this.colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) { prev[curr.name] = curr; return prev; }, {}); if (!isKeyFieldDefined && !keyField) { throw 'Error. No any key column defined in TableHeaderColumn.\n Use \'isKey={true}\' to specify a unique column after version 0.5.4.'; } this.store.setProps({ isPagination: props.pagination, keyField: keyField, colInfos: this.colInfos, multiColumnSearch: props.multiColumnSearch, remote: this.isRemoteDataSource() }); } }, { key: 'getTableData', value: function getTableData() { var result = []; var _props = this.props; var options = _props.options; var pagination = _props.pagination; var sortName = options.defaultSortName || options.sortName; var sortOrder = options.defaultSortOrder || options.sortOrder; var searchText = options.defaultSearch; if (sortName && sortOrder) { this.store.sort(sortOrder, sortName); } if (searchText) { this.store.search(searchText); } if (pagination) { var page = undefined; var sizePerPage = undefined; if (this.store.isChangedPage()) { sizePerPage = this.state.sizePerPage; page = this.state.currPage; } else { sizePerPage = options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0]; page = options.page || 1; } result = this.store.page(page, sizePerPage).get(); } else { result = this.store.get(); } return result; } }, { key: 'getColumnsDescription', value: function getColumnsDescription(_ref) { var children = _ref.children; return _react2['default'].Children.map(children, function (column, i) { return { name: column.props.dataField, align: column.props.dataAlign, sort: column.props.dataSort, format: column.props.dataFormat, formatExtraData: column.props.formatExtraData, filterFormatted: column.props.filterFormatted, filterValue: column.props.filterValue, editable: column.props.editable, customEditor: column.props.customEditor, hidden: column.props.hidden, hiddenOnInsert: column.props.hiddenOnInsert, searchable: column.props.searchable, className: column.props.columnClassName, columnTitle: column.props.columnTitle, width: column.props.width, text: column.props.children, sortFunc: column.props.sortFunc, sortFuncExtraData: column.props.sortFuncExtraData, 'export': column.props['export'], index: i }; }); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { this.initTable(nextProps); var options = nextProps.options; var selectRow = nextProps.selectRow; this.store.setData(nextProps.data.slice()); // from #481 var page = this.state.currPage; if (this.props.options.page !== options.page) { page = options.page; } // from #481 var sizePerPage = this.state.sizePerPage; if (this.props.options.sizePerPage !== options.sizePerPage) { sizePerPage = options.sizePerPage; } if (this.isRemoteDataSource()) { this.setState({ data: nextProps.data.slice(), currPage: page, sizePerPage: sizePerPage }); } else { // #125 // remove !options.page for #709 if (page > Math.ceil(nextProps.data.length / sizePerPage)) { page = 1; } var sortInfo = this.store.getSortInfo(); var sortField = options.sortName || (sortInfo ? sortInfo.sortField : undefined); var sortOrder = options.sortOrder || (sortInfo ? sortInfo.order : undefined); if (sortField && sortOrder) this.store.sort(sortOrder, sortField); var data = this.store.page(page, sizePerPage).get(); this.setState({ data: data, currPage: page, sizePerPage: sizePerPage }); } if (selectRow && selectRow.selected) { // set default select rows to store. var copy = selectRow.selected.slice(); this.store.setSelectedRowKey(copy); this.setState({ selectedRowKeys: copy }); } } }, { key: 'componentDidMount', value: function componentDidMount() { this._adjustTable(); window.addEventListener('resize', this._adjustTable); this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { window.removeEventListener('resize', this._adjustTable); this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader); if (this.filter) { this.filter.removeAllListeners('onFilterChange'); } } }, { key: 'componentDidUpdate', value: function componentDidUpdate() { this._adjustTable(); this._attachCellEditFunc(); if (this.props.options.afterTableComplete) { this.props.options.afterTableComplete(); } } }, { key: '_attachCellEditFunc', value: function _attachCellEditFunc() { var cellEdit = this.props.cellEdit; if (cellEdit) { this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this); if (cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE) { this.props.selectRow.clickToSelect = false; } } } /** * Returns true if in the current configuration, * the datagrid should load its data remotely. * * @param {Object} [props] Optional. If not given, this.props will be used * @return {Boolean} */ }, { key: 'isRemoteDataSource', value: function isRemoteDataSource(props) { return (props || this.props).remote; } }, { key: 'render', value: function render() { var style = { height: this.props.height, maxHeight: this.props.maxHeight }; var columns = this.getColumnsDescription(this.props); var sortInfo = this.store.getSortInfo(); var pagination = this.renderPagination(); var toolBar = this.renderToolBar(); var tableFilter = this.renderTableFilter(columns); var isSelectAll = this.isSelectAll(); var sortIndicator = this.props.options.sortIndicator; if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true; return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])('react-bs-table-container', this.props.containerClass), style: this.props.containerStyle }, toolBar, _react2['default'].createElement( 'div', { ref: 'table', className: (0, _classnames2['default'])('react-bs-table', this.props.tableContainerClass), style: _extends({}, style, this.props.tableStyle), onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, _react2['default'].createElement( _TableHeader2['default'], { ref: 'header', headerContainerClass: this.props.headerContainerClass, tableHeaderClass: this.props.tableHeaderClass, style: this.props.headerStyle, rowSelectType: this.props.selectRow.mode, customComponent: this.props.selectRow.customComponent, hideSelectColumn: this.props.selectRow.hideSelectColumn, sortName: sortInfo ? sortInfo.sortField : undefined, sortOrder: sortInfo ? sortInfo.order : undefined, sortIndicator: sortIndicator, onSort: this.handleSort, onSelectAllRow: this.handleSelectAllRow, bordered: this.props.bordered, condensed: this.props.condensed, isFiltered: this.filter ? true : false, isSelectAll: isSelectAll }, this.props.children ), _react2['default'].createElement(_TableBody2['default'], { ref: 'body', bodyContainerClass: this.props.bodyContainerClass, tableBodyClass: this.props.tableBodyClass, style: _extends({}, style, this.props.bodyStyle), data: this.state.data, columns: columns, trClassName: this.props.trClassName, striped: this.props.striped, bordered: this.props.bordered, hover: this.props.hover, keyField: this.store.getKeyField(), condensed: this.props.condensed, selectRow: this.props.selectRow, cellEdit: this.props.cellEdit, selectedRowKeys: this.state.selectedRowKeys, onRowClick: this.handleRowClick, onRowMouseOver: this.handleRowMouseOver, onRowMouseOut: this.handleRowMouseOut, onSelectRow: this.handleSelectRow, noDataText: this.props.options.noDataText }) ), tableFilter, pagination ); } }, { key: 'isSelectAll', value: function isSelectAll() { if (this.store.isEmpty()) return false; var unselectable = this.props.selectRow.unselectable; var defaultSelectRowKeys = this.store.getSelectedRowKeys(); var allRowKeys = this.store.getAllRowkey(); if (defaultSelectRowKeys.length === 0) return false; var match = 0; var noFound = 0; var unSelectableCnt = 0; defaultSelectRowKeys.forEach(function (selected) { if (allRowKeys.indexOf(selected) !== -1) match++;else noFound++; if (unselectable && unselectable.indexOf(selected) !== -1) unSelectableCnt++; }); if (noFound === defaultSelectRowKeys.length) return false; if (match === allRowKeys.length) { return true; } else { if (unselectable && match <= unSelectableCnt && unSelectableCnt === unselectable.length) return false;else return 'indeterminate'; } // return (match === allRowKeys.length) ? true : 'indeterminate'; } }, { key: 'cleanSelected', value: function cleanSelected() { this.store.setSelectedRowKey([]); this.setState({ selectedRowKeys: [] }); } }, { key: 'handleEditCell', value: function handleEditCell(newVal, rowIndex, colIndex) { var onCellEdit = this.props.options.onCellEdit; var _props$cellEdit = this.props.cellEdit; var beforeSaveCell = _props$cellEdit.beforeSaveCell; var afterSaveCell = _props$cellEdit.afterSaveCell; var fieldName = undefined; _react2['default'].Children.forEach(this.props.children, function (column, i) { if (i === colIndex) { fieldName = column.props.dataField; return false; } }); if (beforeSaveCell) { var isValid = beforeSaveCell(this.state.data[rowIndex], fieldName, newVal); if (!isValid && typeof isValid !== 'undefined') { this.setState({ data: this.store.get() }); return; } } if (onCellEdit) { newVal = onCellEdit(this.state.data[rowIndex], fieldName, newVal); } if (this.isRemoteDataSource()) { if (afterSaveCell) { afterSaveCell(this.state.data[rowIndex], fieldName, newVal); } return; } var result = this.store.edit(newVal, rowIndex, fieldName).get(); this.setState({ data: result }); if (afterSaveCell) { afterSaveCell(this.state.data[rowIndex], fieldName, newVal); } } }, { key: 'handleAddRowAtBegin', value: function handleAddRowAtBegin(newObj) { try { this.store.addAtBegin(newObj); } catch (e) { return e; } this._handleAfterAddingRow(newObj); } }, { key: 'getSizePerPage', value: function getSizePerPage() { return this.state.sizePerPage; } }, { key: 'getCurrentPage', value: function getCurrentPage() { return this.state.currPage; } }, { key: 'getTableDataIgnorePaging', value: function getTableDataIgnorePaging() { return this.store.getCurrentDisplayData(); } }, { key: 'deleteRow', value: function deleteRow(dropRowKeys) { var onDeleteRow = this.props.options.onDeleteRow; if (onDeleteRow) { onDeleteRow(dropRowKeys); } this.store.setSelectedRowKey([]); // clear selected row key if (this.isRemoteDataSource()) { if (this.props.options.afterDeleteRow) { this.props.options.afterDeleteRow(dropRowKeys); } return; } this.store.remove(dropRowKeys); // remove selected Row var result = undefined; if (this.props.pagination) { var sizePerPage = this.state.sizePerPage; var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage); var currPage = this.state.currPage; if (currPage > currLastPage) currPage = currLastPage; result = this.store.page(currPage, sizePerPage).get(); this.setState({ data: result, selectedRowKeys: this.store.getSelectedRowKeys(), currPage: currPage }); } else { result = this.store.get(); this.setState({ data: result, selectedRowKeys: this.store.getSelectedRowKeys() }); } if (this.props.options.afterDeleteRow) { this.props.options.afterDeleteRow(dropRowKeys); } } }, { key: 'renderPagination', value: function renderPagination() { if (this.props.pagination) { var dataSize = undefined; if (this.isRemoteDataSource()) { dataSize = this.props.fetchInfo.dataTotalSize; } else { dataSize = this.store.getDataNum(); } var options = this.props.options; if (Math.ceil(dataSize / this.state.sizePerPage) <= 1 && this.props.ignoreSinglePage) return null; return _react2['default'].createElement( 'div', { className: 'react-bs-table-pagination' }, _react2['default'].createElement(_paginationPaginationList2['default'], { ref: 'pagination', currPage: this.state.currPage, changePage: this.handlePaginationData, sizePerPage: this.state.sizePerPage, sizePerPageList: options.sizePerPageList || _Const2['default'].SIZE_PER_PAGE_LIST, pageStartIndex: options.pageStartIndex, paginationShowsTotal: options.paginationShowsTotal, paginationSize: options.paginationSize || _Const2['default'].PAGINATION_SIZE, remote: this.isRemoteDataSource(), dataSize: dataSize, onSizePerPageList: options.onSizePerPageList, prePage: options.prePage || _Const2['default'].PRE_PAGE, nextPage: options.nextPage || _Const2['default'].NEXT_PAGE, firstPage: options.firstPage || _Const2['default'].FIRST_PAGE, lastPage: options.lastPage || _Const2['default'].LAST_PAGE, hideSizePerPage: options.hideSizePerPage }) ); } return null; } }, { key: 'renderToolBar', value: function renderToolBar() { var _props2 = this.props; var selectRow = _props2.selectRow; var insertRow = _props2.insertRow; var deleteRow = _props2.deleteRow; var search = _props2.search; var children = _props2.children; var enableShowOnlySelected = selectRow && selectRow.showOnlySelected; if (enableShowOnlySelected || insertRow || deleteRow || search || this.props.exportCSV) { var columns = undefined; if (Array.isArray(children)) { columns = children.map(function (column, r) { var props = column.props; return { name: props.children, field: props.dataField, hiddenOnInsert: props.hiddenOnInsert, // when you want same auto generate value and not allow edit, example ID field autoValue: props.autoValue || false, // for create editor, no params for column.editable() indicate that editor for new row editable: props.editable && typeof props.editable === 'function' ? props.editable() : props.editable, format: props.dataFormat ? function (value) { return props.dataFormat(value, null, props.formatExtraData, r).replace(/<.*?>/g, ''); } : false }; }); } else { columns = [{ name: children.props.children, field: children.props.dataField, editable: children.props.editable, hiddenOnInsert: children.props.hiddenOnInsert }]; } return _react2['default'].createElement( 'div', { className: 'react-bs-table-tool-bar' }, _react2['default'].createElement(_toolbarToolBar2['default'], { defaultSearch: this.props.options.defaultSearch, clearSearch: this.props.options.clearSearch, searchDelayTime: this.props.options.searchDelayTime, enableInsert: insertRow, enableDelete: deleteRow, enableSearch: search, enableExportCSV: this.props.exportCSV, enableShowOnlySelected: enableShowOnlySelected, columns: columns, searchPlaceholder: this.props.searchPlaceholder, exportCSVText: this.props.options.exportCSVText, insertText: this.props.options.insertText, deleteText: this.props.options.deleteText, saveText: this.props.options.saveText, closeText: this.props.options.closeText, ignoreEditable: this.props.options.ignoreEditable, onAddRow: this.handleAddRow, onDropRow: this.handleDropRow, onSearch: this.handleSearch, onExportCSV: this.handleExportCSV, onShowOnlySelected: this.handleShowOnlySelected }) ); } else { return null; } } }, { key: 'renderTableFilter', value: function renderTableFilter(columns) { if (this.props.columnFilter) { return _react2['default'].createElement(_TableFilter2['default'], { columns: columns, rowSelectType: this.props.selectRow.mode, onFilter: this.handleFilterData }); } else { return null; } } }, { key: '_handleAfterAddingRow', value: function _handleAfterAddingRow(newObj) { var result = undefined; if (this.props.pagination) { // if pagination is enabled and insert row be trigger, change to last page var sizePerPage = this.state.sizePerPage; var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage); result = this.store.page(currLastPage, sizePerPage).get(); this.setState({ data: result, currPage: currLastPage }); } else { result = this.store.get(); this.setState({ data: result }); } if (this.props.options.afterInsertRow) { this.props.options.afterInsertRow(newObj); } } }]); return BootstrapTable; })(_react.Component); BootstrapTable.propTypes = { keyField: _react.PropTypes.string, height: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), maxHeight: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), data: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]), remote: _react.PropTypes.bool, // remote data, default is false striped: _react.PropTypes.bool, bordered: _react.PropTypes.bool, hover: _react.PropTypes.bool, condensed: _react.PropTypes.bool, pagination: _react.PropTypes.bool, searchPlaceholder: _react.PropTypes.string, selectRow: _react.PropTypes.shape({ mode: _react.PropTypes.oneOf([_Const2['default'].ROW_SELECT_NONE, _Const2['default'].ROW_SELECT_SINGLE, _Const2['default'].ROW_SELECT_MULTI]), customComponent: _react.PropTypes.func, bgColor: _react.PropTypes.string, selected: _react.PropTypes.array, onSelect: _react.PropTypes.func, onSelectAll: _react.PropTypes.func, clickToSelect: _react.PropTypes.bool, hideSelectColumn: _react.PropTypes.bool, clickToSelectAndEditCell: _react.PropTypes.bool, showOnlySelected: _react.PropTypes.bool, unselectable: _react.PropTypes.array }), cellEdit: _react.PropTypes.shape({ mode: _react.PropTypes.string, blurToSave: _react.PropTypes.bool, beforeSaveCell: _react.PropTypes.func, afterSaveCell: _react.PropTypes.func }), insertRow: _react.PropTypes.bool, deleteRow: _react.PropTypes.bool, search: _react.PropTypes.bool, columnFilter: _react.PropTypes.bool, trClassName: _react.PropTypes.any, tableStyle: _react.PropTypes.object, containerStyle: _react.PropTypes.object, headerStyle: _react.PropTypes.object, bodyStyle: _react.PropTypes.object, containerClass: _react.PropTypes.string, tableContainerClass: _react.PropTypes.string, headerContainerClass: _react.PropTypes.string, bodyContainerClass: _react.PropTypes.string, tableHeaderClass: _react.PropTypes.string, tableBodyClass: _react.PropTypes.string, options: _react.PropTypes.shape({ clearSearch: _react.PropTypes.bool, sortName: _react.PropTypes.string, sortOrder: _react.PropTypes.string, defaultSortName: _react.PropTypes.string, defaultSortOrder: _react.PropTypes.string, sortIndicator: _react.PropTypes.bool, afterTableComplete: _react.PropTypes.func, afterDeleteRow: _react.PropTypes.func, afterInsertRow: _react.PropTypes.func, afterSearch: _react.PropTypes.func, afterColumnFilter: _react.PropTypes.func, onRowClick: _react.PropTypes.func, page: _react.PropTypes.number, pageStartIndex: _react.PropTypes.number, paginationShowsTotal: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), sizePerPageList: _react.PropTypes.array, sizePerPage: _react.PropTypes.number, paginationSize: _react.PropTypes.number, hideSizePerPage: _react.PropTypes.bool, onSortChange: _react.PropTypes.func, onPageChange: _react.PropTypes.func, onSizePerPageList: _react.PropTypes.func, onFilterChange: _react2['default'].PropTypes.func, onSearchChange: _react2['default'].PropTypes.func, onAddRow: _react2['default'].PropTypes.func, onExportToCSV: _react2['default'].PropTypes.func, onCellEdit: _react2['default'].PropTypes.func, noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]), handleConfirmDeleteRow: _react.PropTypes.func, prePage: _react.PropTypes.string, nextPage: _react.PropTypes.string, firstPage: _react.PropTypes.string, lastPage: _react.PropTypes.string, searchDelayTime: _react.PropTypes.number, exportCSVText: _react.PropTypes.string, insertText: _react.PropTypes.string, deleteText: _react.PropTypes.string, saveText: _react.PropTypes.string, closeText: _react.PropTypes.string, ignoreEditable: _react.PropTypes.bool, defaultSearch: _react.PropTypes.string }), fetchInfo: _react.PropTypes.shape({ dataTotalSize: _react.PropTypes.number }), exportCSV: _react.PropTypes.bool, csvFileName: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]), ignoreSinglePage: _react.PropTypes.bool }; BootstrapTable.defaultProps = { height: '100%', maxHeight: undefined, striped: false, bordered: true, hover: false, condensed: false, pagination: false, searchPlaceholder: undefined, selectRow: { mode: _Const2['default'].ROW_SELECT_NONE, bgColor: _Const2['default'].ROW_SELECT_BG_COLOR, selected: [], onSelect: undefined, onSelectAll: undefined, clickToSelect: false, hideSelectColumn: false, clickToSelectAndEditCell: false, showOnlySelected: false, unselectable: [], customComponent: undefined }, cellEdit: { mode: _Const2['default'].CELL_EDIT_NONE, blurToSave: false, beforeSaveCell: undefined, afterSaveCell: undefined }, insertRow: false, deleteRow: false, search: false, multiColumnSearch: false, columnFilter: false, trClassName: '', tableStyle: undefined, containerStyle: undefined, headerStyle: undefined, bodyStyle: undefined, containerClass: null, tableContainerClass: null, headerContainerClass: null, bodyContainerClass: null, tableHeaderClass: null, tableBodyClass: null, options: { clearSearch: false, sortName: undefined, sortOrder: undefined, defaultSortName: undefined, defaultSortOrder: undefined, sortIndicator: true, afterTableComplete: undefined, afterDeleteRow: undefined, afterInsertRow: undefined, afterSearch: undefined, afterColumnFilter: undefined, onRowClick: undefined, onMouseLeave: undefined, onMouseEnter: undefined, onRowMouseOut: undefined, onRowMouseOver: undefined, page: undefined, paginationShowsTotal: false, sizePerPageList: _Const2['default'].SIZE_PER_PAGE_LIST, sizePerPage: undefined, paginationSize: _Const2['default'].PAGINATION_SIZE, hideSizePerPage: false, onSizePerPageList: undefined, noDataText: undefined, handleConfirmDeleteRow: undefined, prePage: _Const2['default'].PRE_PAGE, nextPage: _Const2['default'].NEXT_PAGE, firstPage: _Const2['default'].FIRST_PAGE, lastPage: _Const2['default'].LAST_PAGE, pageStartIndex: undefined, searchDelayTime: undefined, exportCSVText: _Const2['default'].EXPORT_CSV_TEXT, insertText: _Const2['default'].INSERT_BTN_TEXT, deleteText: _Const2['default'].DELETE_BTN_TEXT, saveText: _Const2['default'].SAVE_BTN_TEXT, closeText: _Const2['default'].CLOSE_BTN_TEXT, ignoreEditable: false, defaultSearch: '' }, fetchInfo: { dataTotalSize: 0 }, exportCSV: false, csvFileName: 'spreadsheet.csv', ignoreSinglePage: false }; exports['default'] = BootstrapTable; module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; 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; } }()); /***/ }, /* 4 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = { SORT_DESC: 'desc', SORT_ASC: 'asc', SIZE_PER_PAGE: 10, NEXT_PAGE: '>', LAST_PAGE: '>>', PRE_PAGE: '<', FIRST_PAGE: '<<', PAGE_START_INDEX: 1, ROW_SELECT_BG_COLOR: '', ROW_SELECT_NONE: 'none', ROW_SELECT_SINGLE: 'radio', ROW_SELECT_MULTI: 'checkbox', CELL_EDIT_NONE: 'none', CELL_EDIT_CLICK: 'click', CELL_EDIT_DBCLICK: 'dbclick', SIZE_PER_PAGE_LIST: [10, 25, 30, 50], PAGINATION_SIZE: 5, NO_DATA_TEXT: 'There is no data to display', SHOW_ONLY_SELECT: 'Show Selected Only', SHOW_ALL: 'Show All', EXPORT_CSV_TEXT: 'Export to CSV', INSERT_BTN_TEXT: 'New', DELETE_BTN_TEXT: 'Delete', SAVE_BTN_TEXT: 'Save', CLOSE_BTN_TEXT: 'Close', FILTER_DELAY: 500, FILTER_TYPE: { TEXT: 'TextFilter', REGEX: 'RegexFilter', SELECT: 'SelectFilter', NUMBER: 'NumberFilter', DATE: 'DateFilter', CUSTOM: 'CustomFilter' } }; module.exports = exports['default']; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _SelectRowHeaderColumn = __webpack_require__(7); var _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn); var Checkbox = (function (_Component) { _inherits(Checkbox, _Component); function Checkbox() { _classCallCheck(this, Checkbox); _get(Object.getPrototypeOf(Checkbox.prototype), 'constructor', this).apply(this, arguments); } _createClass(Checkbox, [{ key: 'componentDidMount', value: function componentDidMount() { this.update(this.props.checked); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(props) { this.update(props.checked); } }, { key: 'update', value: function update(checked) { _reactDom2['default'].findDOMNode(this).indeterminate = checked === 'indeterminate'; } }, { key: 'render', value: function render() { return _react2['default'].createElement('input', { className: 'react-bs-select-all', type: 'checkbox', checked: this.props.checked, onChange: this.props.onChange }); } }]); return Checkbox; })(_react.Component); var TableHeader = (function (_Component2) { _inherits(TableHeader, _Component2); function TableHeader() { _classCallCheck(this, TableHeader); _get(Object.getPrototypeOf(TableHeader.prototype), 'constructor', this).apply(this, arguments); } _createClass(TableHeader, [{ key: 'render', value: function render() { var _this = this; var containerClasses = (0, _classnames2['default'])('react-bs-container-header', 'table-header-wrapper', this.props.headerContainerClass); var tableClasses = (0, _classnames2['default'])('table', 'table-hover', { 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed }, this.props.tableHeaderClass); var selectRowHeaderCol = null; if (!this.props.hideSelectColumn) selectRowHeaderCol = this.renderSelectRowHeader(); var i = 0; return _react2['default'].createElement( 'div', { ref: 'container', className: containerClasses, style: this.props.style }, _react2['default'].createElement( 'table', { className: tableClasses }, _react2['default'].createElement( 'thead', null, _react2['default'].createElement( 'tr', { ref: 'header' }, selectRowHeaderCol, _react2['default'].Children.map(this.props.children, function (elm) { var _props = _this.props; var sortIndicator = _props.sortIndicator; var sortName = _props.sortName; var sortOrder = _props.sortOrder; var onSort = _props.onSort; var _elm$props = elm.props; var dataField = _elm$props.dataField; var dataSort = _elm$props.dataSort; var sort = dataSort && dataField === sortName ? sortOrder : undefined; return _react2['default'].cloneElement(elm, { key: i++, onSort: onSort, sort: sort, sortIndicator: sortIndicator }); }) ) ) ) ); } }, { key: 'renderSelectRowHeader', value: function renderSelectRowHeader() { if (this.props.customComponent) { var CustomComponent = this.props.customComponent; return _react2['default'].createElement( _SelectRowHeaderColumn2['default'], null, _react2['default'].createElement(CustomComponent, { type: 'checkbox', checked: this.props.isSelectAll, indeterminate: this.props.isSelectAll === 'indeterminate', disabled: false, onChange: this.props.onSelectAllRow, rowIndex: 'Header' }) ); } else if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_SINGLE) { return _react2['default'].createElement(_SelectRowHeaderColumn2['default'], null); } else if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_MULTI) { return _react2['default'].createElement( _SelectRowHeaderColumn2['default'], null, _react2['default'].createElement(Checkbox, { onChange: this.props.onSelectAllRow, checked: this.props.isSelectAll }) ); } else { return null; } } }]); return TableHeader; })(_react.Component); TableHeader.propTypes = { headerContainerClass: _react.PropTypes.string, tableHeaderClass: _react.PropTypes.string, style: _react.PropTypes.object, rowSelectType: _react.PropTypes.string, onSort: _react.PropTypes.func, onSelectAllRow: _react.PropTypes.func, sortName: _react.PropTypes.string, sortOrder: _react.PropTypes.string, hideSelectColumn: _react.PropTypes.bool, bordered: _react.PropTypes.bool, condensed: _react.PropTypes.bool, isFiltered: _react.PropTypes.bool, isSelectAll: _react.PropTypes.oneOf([true, 'indeterminate', false]), sortIndicator: _react.PropTypes.bool, customComponent: _react.PropTypes.func }; exports['default'] = TableHeader; module.exports = exports['default']; /***/ }, /* 6 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_6__; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var SelectRowHeaderColumn = (function (_Component) { _inherits(SelectRowHeaderColumn, _Component); function SelectRowHeaderColumn() { _classCallCheck(this, SelectRowHeaderColumn); _get(Object.getPrototypeOf(SelectRowHeaderColumn.prototype), 'constructor', this).apply(this, arguments); } _createClass(SelectRowHeaderColumn, [{ key: 'render', value: function render() { return _react2['default'].createElement( 'th', { style: { textAlign: 'center' } }, this.props.children ); } }]); return SelectRowHeaderColumn; })(_react.Component); SelectRowHeaderColumn.propTypes = { children: _react.PropTypes.node }; exports['default'] = SelectRowHeaderColumn; module.exports = exports['default']; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x3, _x4, _x5) { var _again = true; _function: while (_again) { var object = _x3, property = _x4, receiver = _x5; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x3 = parent; _x4 = property; _x5 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _TableRow = __webpack_require__(9); var _TableRow2 = _interopRequireDefault(_TableRow); var _TableColumn = __webpack_require__(10); var _TableColumn2 = _interopRequireDefault(_TableColumn); var _TableEditColumn = __webpack_require__(11); var _TableEditColumn2 = _interopRequireDefault(_TableEditColumn); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var isFun = function isFun(obj) { return obj && typeof obj === 'function'; }; var TableBody = (function (_Component) { _inherits(TableBody, _Component); function TableBody(props) { var _this = this; _classCallCheck(this, TableBody); _get(Object.getPrototypeOf(TableBody.prototype), 'constructor', this).call(this, props); this.handleRowMouseOut = function (rowIndex, event) { var targetRow = _this.props.data[rowIndex]; _this.props.onRowMouseOut(targetRow, event); }; this.handleRowMouseOver = function (rowIndex, event) { var targetRow = _this.props.data[rowIndex]; _this.props.onRowMouseOver(targetRow, event); }; this.handleRowClick = function (rowIndex) { var selectedRow = undefined; var _props = _this.props; var data = _props.data; var onRowClick = _props.onRowClick; data.forEach(function (row, i) { if (i === rowIndex - 1) { selectedRow = row; } }); onRowClick(selectedRow); }; this.handleSelectRow = function (rowIndex, isSelected, e) { var selectedRow = undefined; var _props2 = _this.props; var data = _props2.data; var onSelectRow = _props2.onSelectRow; data.forEach(function (row, i) { if (i === rowIndex - 1) { selectedRow = row; return false; } }); onSelectRow(selectedRow, isSelected, e); }; this.handleSelectRowColumChange = function (e, rowIndex) { if (!_this.props.selectRow.clickToSelect || !_this.props.selectRow.clickToSelectAndEditCell) { _this.handleSelectRow(rowIndex + 1, e.currentTarget.checked, e); } }; this.handleEditCell = function (rowIndex, columnIndex, e) { if (_this._isSelectRowDefined()) { columnIndex--; if (_this.props.selectRow.hideSelectColumn) columnIndex++; } rowIndex--; var stateObj = { currEditCell: { rid: rowIndex, cid: columnIndex } }; if (_this.props.selectRow.clickToSelectAndEditCell && _this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_DBCLICK) { var selected = _this.props.selectedRowKeys.indexOf(_this.props.data[rowIndex][_this.props.keyField]) !== -1; _this.handleSelectRow(rowIndex + 1, !selected, e); } _this.setState(stateObj); }; this.handleCompleteEditCell = function (newVal, rowIndex, columnIndex) { _this.setState({ currEditCell: null }); if (newVal !== null) { _this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex); } }; this.state = { currEditCell: null }; } _createClass(TableBody, [{ key: 'render', value: function render() { var tableClasses = (0, _classnames2['default'])('table', { 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-hover': this.props.hover, 'table-condensed': this.props.condensed }, this.props.tableBodyClass); var unselectable = this.props.selectRow.unselectable || []; var isSelectRowDefined = this._isSelectRowDefined(); var tableHeader = this.renderTableHeader(isSelectRowDefined); var inputType = this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE ? 'radio' : 'checkbox'; var CustomComponent = this.props.selectRow.customComponent; var tableRows = this.props.data.map(function (data, r) { var tableColumns = this.props.columns.map(function (column, i) { var fieldValue = data[column.name]; if (column.name !== this.props.keyField && // Key field can't be edit column.editable && // column is editable? default is true, user can set it false this.state.currEditCell !== null && this.state.currEditCell.rid === r && this.state.currEditCell.cid === i) { var editable = column.editable; var format = column.format ? function (value) { return column.format(value, data, column.formatExtraData, r).replace(/<.*?>/g, ''); } : false; if (isFun(column.editable)) { editable = column.editable(fieldValue, data, r, i); } return _react2['default'].createElement(_TableEditColumn2['default'], { completeEdit: this.handleCompleteEditCell, // add by bluespring for column editor customize editable: editable, customEditor: column.customEditor, format: column.format ? format : false, key: i, blurToSave: this.props.cellEdit.blurToSave, rowIndex: r, colIndex: i, row: data, fieldValue: fieldValue }); } else { // add by bluespring for className customize var columnChild = fieldValue && fieldValue.toString(); var columnTitle = null; var tdClassName = column.className; if (isFun(column.className)) { tdClassName = column.className(fieldValue, data, r, i); } if (typeof column.format !== 'undefined') { var formattedValue = column.format(fieldValue, data, column.formatExtraData, r); if (!_react2['default'].isValidElement(formattedValue)) { columnChild = _react2['default'].createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } }); } else { columnChild = formattedValue; columnTitle = column.columnTitle && formattedValue ? formattedValue.toString() : null; } } else { columnTitle = column.columnTitle && fieldValue ? fieldValue.toString() : null; } return _react2['default'].createElement( _TableColumn2['default'], { key: i, dataAlign: column.align, className: tdClassName, columnTitle: columnTitle, cellEdit: this.props.cellEdit, hidden: column.hidden, onEdit: this.handleEditCell, width: column.width }, columnChild ); } }, this); var key = data[this.props.keyField]; var disable = unselectable.indexOf(key) !== -1; var selected = this.props.selectedRowKeys.indexOf(key) !== -1; var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected, inputType, disable, CustomComponent, r) : null; // add by bluespring for className customize var trClassName = this.props.trClassName; if (isFun(this.props.trClassName)) { trClassName = this.props.trClassName(data, r); } return _react2['default'].createElement( _TableRow2['default'], { isSelected: selected, key: key, className: trClassName, selectRow: isSelectRowDefined ? this.props.selectRow : undefined, enableCellEdit: this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE, onRowClick: this.handleRowClick, onRowMouseOver: this.handleRowMouseOver, onRowMouseOut: this.handleRowMouseOut, onSelectRow: this.handleSelectRow, unselectableRow: disable }, selectRowColumn, tableColumns ); }, this); if (tableRows.length === 0) { tableRows.push(_react2['default'].createElement( _TableRow2['default'], { key: '##table-empty##' }, _react2['default'].createElement( 'td', { colSpan: this.props.columns.length + (isSelectRowDefined ? 1 : 0), className: 'react-bs-table-no-data' }, this.props.noDataText || _Const2['default'].NO_DATA_TEXT ) )); } return _react2['default'].createElement( 'div', { ref: 'container', className: (0, _classnames2['default'])('react-bs-container-body', this.props.bodyContainerClass), style: this.props.style }, _react2['default'].createElement( 'table', { className: tableClasses }, tableHeader, _react2['default'].createElement( 'tbody', { ref: 'tbody' }, tableRows ) ) ); } }, { key: 'renderTableHeader', value: function renderTableHeader(isSelectRowDefined) { var selectRowHeader = null; if (isSelectRowDefined) { var style = { width: 30, minWidth: 30 }; if (!this.props.selectRow.hideSelectColumn) { selectRowHeader = _react2['default'].createElement('col', { style: style, key: -1 }); } } var theader = this.props.columns.map(function (column, i) { var style = { display: column.hidden ? 'none' : null }; if (column.width) { var width = parseInt(column.width, 10); style.width = width; /** add min-wdth to fix user assign column width not eq offsetWidth in large column table **/ style.minWidth = width; } return _react2['default'].createElement('col', { style: style, key: i, className: column.className }); }); return _react2['default'].createElement( 'colgroup', { ref: 'header' }, selectRowHeader, theader ); } }, { key: 'renderSelectRowColumn', value: function renderSelectRowColumn(selected, inputType, disabled) { var _this2 = this; var CustomComponent = arguments.length <= 3 || arguments[3] === undefined ? null : arguments[3]; var rowIndex = arguments.length <= 4 || arguments[4] === undefined ? null : arguments[4]; return _react2['default'].createElement( _TableColumn2['default'], { dataAlign: 'center' }, CustomComponent ? _react2['default'].createElement(CustomComponent, { type: inputType, checked: selected, disabled: disabled, rowIndex: rowIndex, onChange: function (e) { return _this2.handleSelectRowColumChange(e, e.currentTarget.parentElement.parentElement.parentElement.rowIndex); } }) : _react2['default'].createElement('input', { type: inputType, checked: selected, disabled: disabled, onChange: function (e) { return _this2.handleSelectRowColumChange(e, e.currentTarget.parentElement.parentElement.rowIndex); } }) ); } }, { key: '_isSelectRowDefined', value: function _isSelectRowDefined() { return this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2['default'].ROW_SELECT_MULTI; } }]); return TableBody; })(_react.Component); TableBody.propTypes = { data: _react.PropTypes.array, columns: _react.PropTypes.array, striped: _react.PropTypes.bool, bordered: _react.PropTypes.bool, hover: _react.PropTypes.bool, condensed: _react.PropTypes.bool, keyField: _react.PropTypes.string, selectedRowKeys: _react.PropTypes.array, onRowClick: _react.PropTypes.func, onSelectRow: _react.PropTypes.func, noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]), style: _react.PropTypes.object, tableBodyClass: _react.PropTypes.string, bodyContainerClass: _react.PropTypes.string }; exports['default'] = TableBody; module.exports = exports['default']; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var TableRow = (function (_Component) { _inherits(TableRow, _Component); function TableRow(props) { var _this = this; _classCallCheck(this, TableRow); _get(Object.getPrototypeOf(TableRow.prototype), 'constructor', this).call(this, props); this.rowClick = function (e) { if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT' && e.target.tagName !== 'TEXTAREA') { (function () { var rowIndex = e.currentTarget.rowIndex + 1; var _props = _this.props; var selectRow = _props.selectRow; var unselectableRow = _props.unselectableRow; var isSelected = _props.isSelected; var onSelectRow = _props.onSelectRow; if (selectRow) { if (selectRow.clickToSelect && !unselectableRow) { onSelectRow(rowIndex, !isSelected, e); } else if (selectRow.clickToSelectAndEditCell && !unselectableRow) { _this.clickNum++; /** if clickToSelectAndEditCell is enabled, * there should be a delay to prevent a selection changed when * user dblick to edit cell on same row but different cell **/ setTimeout(function () { if (_this.clickNum === 1) { onSelectRow(rowIndex, !isSelected, e); } _this.clickNum = 0; }, 200); } } if (_this.props.onRowClick) _this.props.onRowClick(rowIndex); })(); } }; this.rowMouseOut = function (e) { if (_this.props.onRowMouseOut) { _this.props.onRowMouseOut(e.currentTarget.rowIndex, e); } }; this.rowMouseOver = function (e) { if (_this.props.onRowMouseOver) { _this.props.onRowMouseOver(e.currentTarget.rowIndex, e); } }; this.clickNum = 0; } _createClass(TableRow, [{ key: 'render', value: function render() { this.clickNum = 0; var trCss = { style: { backgroundColor: this.props.isSelected ? this.props.selectRow.bgColor : null }, className: (0, _classnames2['default'])(this.props.isSelected ? this.props.selectRow.className : null, this.props.className) }; if (this.props.selectRow && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell) || this.props.onRowClick) { return _react2['default'].createElement( 'tr', _extends({}, trCss, { onMouseOver: this.rowMouseOver, onMouseOut: this.rowMouseOut, onClick: this.rowClick }), this.props.children ); } else { return _react2['default'].createElement( 'tr', trCss, this.props.children ); } } }]); return TableRow; })(_react.Component); TableRow.propTypes = { isSelected: _react.PropTypes.bool, enableCellEdit: _react.PropTypes.bool, onRowClick: _react.PropTypes.func, onSelectRow: _react.PropTypes.func, onRowMouseOut: _react.PropTypes.func, onRowMouseOver: _react.PropTypes.func, unselectableRow: _react.PropTypes.bool }; TableRow.defaultProps = { onRowClick: undefined }; exports['default'] = TableRow; module.exports = exports['default']; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var TableColumn = (function (_Component) { _inherits(TableColumn, _Component); function TableColumn(props) { var _this = this; _classCallCheck(this, TableColumn); _get(Object.getPrototypeOf(TableColumn.prototype), 'constructor', this).call(this, props); this.handleCellEdit = function (e) { if (_this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) { if (document.selection && document.selection.empty) { document.selection.empty(); } else if (window.getSelection) { var sel = window.getSelection(); sel.removeAllRanges(); } } _this.props.onEdit(e.currentTarget.parentElement.rowIndex + 1, e.currentTarget.cellIndex, e); }; } /* eslint no-unused-vars: [0, { "args": "after-used" }] */ _createClass(TableColumn, [{ key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var children = this.props.children; var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || typeof children !== typeof nextProps.children || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString(); if (shouldUpdated) { return shouldUpdated; } if (typeof children === 'object' && children !== null && children.props !== null) { if (children.props.type === 'checkbox' || children.props.type === 'radio') { shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked || children.props.disabled !== nextProps.children.props.disabled; } else { shouldUpdated = true; } } else { shouldUpdated = shouldUpdated || children !== nextProps.children; } if (shouldUpdated) { return shouldUpdated; } if (!(this.props.cellEdit && nextProps.cellEdit)) { return false; } else { return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode; } } }, { key: 'render', value: function render() { var tdStyle = { textAlign: this.props.dataAlign, display: this.props.hidden ? 'none' : null }; var opts = {}; if (this.props.cellEdit) { if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_CLICK) { opts.onClick = this.handleCellEdit; } else if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) { opts.onDoubleClick = this.handleCellEdit; } } return _react2['default'].createElement( 'td', _extends({ style: tdStyle, title: this.props.columnTitle, className: this.props.className }, opts), this.props.children ); } }]); return TableColumn; })(_react.Component); TableColumn.propTypes = { dataAlign: _react.PropTypes.string, hidden: _react.PropTypes.bool, className: _react.PropTypes.string, columnTitle: _react.PropTypes.string, children: _react.PropTypes.node }; TableColumn.defaultProps = { dataAlign: 'left', hidden: false, className: '' }; exports['default'] = TableColumn; module.exports = exports['default']; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Editor = __webpack_require__(12); var _Editor2 = _interopRequireDefault(_Editor); var _NotificationJs = __webpack_require__(13); var _NotificationJs2 = _interopRequireDefault(_NotificationJs); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var TableEditColumn = (function (_Component) { _inherits(TableEditColumn, _Component); function TableEditColumn(props) { var _this = this; _classCallCheck(this, TableEditColumn); _get(Object.getPrototypeOf(TableEditColumn.prototype), 'constructor', this).call(this, props); this.handleKeyPress = function (e) { if (e.keyCode === 13) { // Pressed ENTER var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value; if (!_this.validator(value)) { return; } _this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex); } else if (e.keyCode === 27) { _this.props.completeEdit(null, _this.props.rowIndex, _this.props.colIndex); } else if (e.type === 'click' && !_this.props.blurToSave) { // textarea click save button var value = e.target.parentElement.firstChild.value; if (!_this.validator(value)) { return; } _this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex); } }; this.handleBlur = function (e) { e.stopPropagation(); if (_this.props.blurToSave) { var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value; if (!_this.validator(value)) { return; } _this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex); } }; this.handleCustomUpdate = function (value) { _this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex); }; this.timeouteClear = 0; this.state = { shakeEditor: false }; } _createClass(TableEditColumn, [{ key: 'validator', // modified by iuculanop // BEGIN value: function validator(value) { var ts = this; var valid = true; if (ts.props.editable.validator) { var input = ts.refs.inputRef; var checkVal = ts.props.editable.validator(value); var responseType = typeof checkVal; if (responseType !== 'object' && checkVal !== true) { valid = false; ts.refs.notifier.notice('error', checkVal, 'Pressed ESC can cancel'); } else if (responseType === 'object' && checkVal.isValid !== true) { valid = false; ts.refs.notifier.notice(checkVal.notification.type, checkVal.notification.msg, checkVal.notification.title); } if (!valid) { // animate input ts.clearTimeout(); ts.setState({ shakeEditor: true }); ts.timeouteClear = setTimeout(function () { ts.setState({ shakeEditor: false }); }, 300); input.focus(); return valid; } } return valid; } // END }, { key: 'clearTimeout', value: (function (_clearTimeout) { function clearTimeout() { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; })(function () { if (this.timeouteClear !== 0) { clearTimeout(this.timeouteClear); this.timeouteClear = 0; } }) }, { key: 'componentDidMount', value: function componentDidMount() { this.refs.inputRef.focus(); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearTimeout(); } }, { key: 'render', value: function render() { var _props = this.props; var editable = _props.editable; var format = _props.format; var customEditor = _props.customEditor; var shakeEditor = this.state.shakeEditor; var attr = { ref: 'inputRef', onKeyDown: this.handleKeyPress, onBlur: this.handleBlur }; var fieldValue = this.props.fieldValue; // put placeholder if exist editable.placeholder && (attr.placeholder = editable.placeholder); var editorClass = (0, _classnames2['default'])({ 'animated': shakeEditor, 'shake': shakeEditor }); var cellEditor = undefined; if (customEditor) { var customEditorProps = _extends({ row: this.props.row }, attr, { defaultValue: fieldValue || '' }, customEditor.customEditorParameters); cellEditor = customEditor.getElement(this.handleCustomUpdate, customEditorProps); } else { fieldValue = fieldValue === 0 ? '0' : fieldValue; cellEditor = (0, _Editor2['default'])(editable, attr, format, editorClass, fieldValue || ''); } return _react2['default'].createElement( 'td', { ref: 'td', style: { position: 'relative' } }, cellEditor, _react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }) ); } }, { key: '_getCheckBoxValue', value: function _getCheckBoxValue(e) { var value = ''; var values = e.currentTarget.value.split(':'); value = e.currentTarget.checked ? values[0] : values[1]; return value; } }]); return TableEditColumn; })(_react.Component); TableEditColumn.propTypes = { completeEdit: _react.PropTypes.func, rowIndex: _react.PropTypes.number, colIndex: _react.PropTypes.number, blurToSave: _react.PropTypes.bool, editable: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]), format: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), row: _react.PropTypes.any, fieldValue: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.bool, _react.PropTypes.number, _react.PropTypes.array, _react.PropTypes.object]) }; exports['default'] = TableEditColumn; module.exports = exports['default']; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var editor = function editor(editable, attr, format, editorClass, defaultValue, ignoreEditable) { if (editable === true || editable === false && ignoreEditable || typeof editable === 'string') { // simple declare var type = editable ? 'text' : editable; return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, className: (editorClass || '') + ' form-control editor edit-text' })); } else if (!editable) { var type = editable ? 'text' : editable; return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, disabled: 'disabled', className: (editorClass || '') + ' form-control editor edit-text' })); } else if (editable && (editable.type === undefined || editable.type === null || editable.type.trim() === '')) { var type = editable ? 'text' : editable; return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue, className: (editorClass || '') + ' form-control editor edit-text' })); } else if (editable.type) { // standard declare // put style if exist editable.style && (attr.style = editable.style); // put class if exist attr.className = (editorClass || '') + ' form-control editor edit-' + editable.type + (editable.className ? ' ' + editable.className : ''); if (editable.type === 'select') { // process select input var options = []; var values = editable.options.values; if (Array.isArray(values)) { (function () { // only can use arrray data for options var rowValue = undefined; options = values.map(function (d, i) { rowValue = format ? format(d) : d; return _react2['default'].createElement( 'option', { key: 'option' + i, value: d }, rowValue ); }); })(); } return _react2['default'].createElement( 'select', _extends({}, attr, { defaultValue: defaultValue }), options ); } else if (editable.type === 'textarea') { var _ret2 = (function () { // process textarea input // put other if exist editable.cols && (attr.cols = editable.cols); editable.rows && (attr.rows = editable.rows); var saveBtn = undefined; var keyUpHandler = attr.onKeyDown; if (keyUpHandler) { attr.onKeyDown = function (e) { if (e.keyCode !== 13) { // not Pressed ENTER keyUpHandler(e); } }; saveBtn = _react2['default'].createElement( 'button', { className: 'btn btn-info btn-xs textarea-save-btn', onClick: keyUpHandler }, 'save' ); } return { v: _react2['default'].createElement( 'div', null, _react2['default'].createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })), saveBtn ) }; })(); if (typeof _ret2 === 'object') return _ret2.v; } else if (editable.type === 'checkbox') { var values = 'true:false'; if (editable.options && editable.options.values) { // values = editable.options.values.split(':'); values = editable.options.values; } attr.className = attr.className.replace('form-control', ''); attr.className += ' checkbox pull-right'; var checked = defaultValue && defaultValue.toString() === values.split(':')[0] ? true : false; return _react2['default'].createElement('input', _extends({}, attr, { type: 'checkbox', value: values, defaultChecked: checked })); } else if (editable.type === 'datetime') { return _react2['default'].createElement('input', _extends({}, attr, { type: 'datetime-local', defaultValue: defaultValue })); } else { // process other input type. as password,url,email... return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', defaultValue: defaultValue })); } } // default return for other case of editable return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', className: (editorClass || '') + ' form-control editor edit-text' })); }; exports['default'] = editor; module.exports = exports['default']; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactToastr = __webpack_require__(14); var ToastrMessageFactory = _react2['default'].createFactory(_reactToastr.ToastMessage.animation); var Notification = (function (_Component) { _inherits(Notification, _Component); function Notification() { _classCallCheck(this, Notification); _get(Object.getPrototypeOf(Notification.prototype), 'constructor', this).apply(this, arguments); } _createClass(Notification, [{ key: 'notice', // allow type is success,info,warning,error value: function notice(type, msg, title) { this.refs.toastr[type](msg, title, { mode: 'single', timeOut: 5000, extendedTimeOut: 1000, showAnimation: 'animated bounceIn', hideAnimation: 'animated bounceOut' }); } }, { key: 'render', value: function render() { return _react2['default'].createElement(_reactToastr.ToastContainer, { ref: 'toastr', toastMessageFactory: ToastrMessageFactory, id: 'toast-container', className: 'toast-top-right' }); } }]); return Notification; })(_react.Component); exports['default'] = Notification; module.exports = exports['default']; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ToastMessage = exports.ToastContainer = undefined; var _ToastContainer = __webpack_require__(15); var _ToastContainer2 = _interopRequireDefault(_ToastContainer); var _ToastMessage = __webpack_require__(23); var _ToastMessage2 = _interopRequireDefault(_ToastMessage); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.ToastContainer = _ToastContainer2.default; exports.ToastMessage = _ToastMessage2.default; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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__(2); var _react2 = _interopRequireDefault(_react); var _reactAddonsUpdate = __webpack_require__(16); var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate); var _ToastMessage = __webpack_require__(23); var _ToastMessage2 = _interopRequireDefault(_ToastMessage); var _lodash = __webpack_require__(30); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ToastContainer = function (_Component) { _inherits(ToastContainer, _Component); function ToastContainer() { var _Object$getPrototypeO; var _temp, _this, _ret; _classCallCheck(this, ToastContainer); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = { toasts: [], toastId: 0, messageList: [] }, _temp), _possibleConstructorReturn(_this, _ret); } _createClass(ToastContainer, [{ key: "error", value: function error(message, title, optionsOverride) { this._notify(this.props.toastType.error, message, title, optionsOverride); } }, { key: "info", value: function info(message, title, optionsOverride) { this._notify(this.props.toastType.info, message, title, optionsOverride); } }, { key: "success", value: function success(message, title, optionsOverride) { this._notify(this.props.toastType.success, message, title, optionsOverride); } }, { key: "warning", value: function warning(message, title, optionsOverride) { this._notify(this.props.toastType.warning, message, title, optionsOverride); } }, { key: "clear", value: function clear() { var _this2 = this; Object.keys(this.refs).forEach(function (key) { _this2.refs[key].hideToast(false); }); } }, { key: "_notify", value: function _notify(type, message, title) { var _this3 = this; var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; if (this.props.preventDuplicates) { if (_lodash2.default.includes(this.state.messageList, message)) { return; } } var key = this.state.toastId++; var toastId = key; var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, { $merge: { type: type, title: title, message: message, toastId: toastId, key: key, ref: "toasts__" + key, handleOnClick: function handleOnClick(e) { if ("function" === typeof optionsOverride.handleOnClick) { optionsOverride.handleOnClick(); } return _this3._handle_toast_on_click(e); }, handleRemove: this._handle_toast_remove.bind(this) } }); var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]); var messageOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [message]); var nextState = (0, _reactAddonsUpdate2.default)(this.state, { toasts: toastOperation, messageList: messageOperation }); this.setState(nextState); } }, { key: "_handle_toast_on_click", value: function _handle_toast_on_click(event) { this.props.onClick(event); if (event.defaultPrevented) { return; } event.preventDefault(); event.stopPropagation(); } }, { key: "_handle_toast_remove", value: function _handle_toast_remove(toastId) { var _this4 = this; if (this.props.preventDuplicates) { this.state.previousMessage = ""; } var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce"); this.state.toasts[operationName](function (found, toast, index) { if (found || toast.toastId !== toastId) { return false; } _this4.setState((0, _reactAddonsUpdate2.default)(_this4.state, { toasts: { $splice: [[index, 1]] }, messageList: { $splice: [[index, 1]] } })); return true; }, false); } }, { key: "render", value: function render() { var _this5 = this; var divProps = _lodash2.default.omit(this.props, ["toastType", "toastMessageFactory", "preventDuplicates", "newestOnTop"]); return _react2.default.createElement( "div", _extends({}, divProps, { "aria-live": "polite", role: "alert" }), this.state.toasts.map(function (toast) { return _this5.props.toastMessageFactory(toast); }) ); } }]); return ToastContainer; }(_react.Component); ToastContainer.propTypes = { toastType: _react.PropTypes.shape({ error: _react.PropTypes.string, info: _react.PropTypes.string, success: _react.PropTypes.string, warning: _react.PropTypes.string }).isRequired, id: _react.PropTypes.string.isRequired, toastMessageFactory: _react.PropTypes.func.isRequired, preventDuplicates: _react.PropTypes.bool.isRequired, newestOnTop: _react.PropTypes.bool.isRequired, onClick: _react.PropTypes.func.isRequired }; ToastContainer.defaultProps = { toastType: { error: "error", info: "info", success: "success", warning: "warning" }, id: "toast-container", toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default.animation), preventDuplicates: true, newestOnTop: true, onClick: function onClick() {} }; exports.default = ToastContainer; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(17); /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the 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 = __webpack_require__(19), _assign = __webpack_require__(20); var keyOf = __webpack_require__(21); var invariant = __webpack_require__(22); var hasOwnProperty = {}.hasOwnProperty; function shallowCopy(x) { if (Array.isArray(x)) { return x.concat(); } else if (x && typeof x === 'object') { return _assign(new x.constructor(), x); } else { return x; } } var COMMAND_PUSH = keyOf({ $push: null }); var COMMAND_UNSHIFT = keyOf({ $unshift: null }); var COMMAND_SPLICE = keyOf({ $splice: null }); var COMMAND_SET = keyOf({ $set: null }); var COMMAND_MERGE = keyOf({ $merge: null }); var COMMAND_APPLY = keyOf({ $apply: null }); var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY]; var ALL_COMMANDS_SET = {}; ALL_COMMANDS_LIST.forEach(function (command) { ALL_COMMANDS_SET[command] = true; }); function invariantArrayCase(value, spec, command) { !Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : _prodInvariant('1', command, value) : void 0; var specValue = spec[command]; !Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. Did you forget to wrap your parameter in an array?', command, specValue) : _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') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : _prodInvariant('3', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : void 0; if (hasOwnProperty.call(spec, COMMAND_SET)) { !(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : _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') ? process.env.NODE_ENV !== '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') ? process.env.NODE_ENV !== '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) ? process.env.NODE_ENV !== '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]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _prodInvariant('8', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : void 0; spec[COMMAND_SPLICE].forEach(function (args) { !Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : _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') ? process.env.NODE_ENV !== '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; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 18 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 19 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @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; /***/ }, /* 20 */ /***/ function(module, exports) { 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }, /* 21 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function keyOf(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.jQuery = exports.animation = undefined; var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactAddonsUpdate = __webpack_require__(16); var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _animationMixin = __webpack_require__(24); var _animationMixin2 = _interopRequireDefault(_animationMixin); var _jQueryMixin = __webpack_require__(29); var _jQueryMixin2 = _interopRequireDefault(_jQueryMixin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function noop() {} var ToastMessageSpec = { displayName: "ToastMessage", getDefaultProps: function getDefaultProps() { var iconClassNames = { error: "toast-error", info: "toast-info", success: "toast-success", warning: "toast-warning" }; return { className: "toast", iconClassNames: iconClassNames, titleClassName: "toast-title", messageClassName: "toast-message", tapToDismiss: true, closeButton: false }; }, handleOnClick: function handleOnClick(event) { this.props.handleOnClick(event); if (this.props.tapToDismiss) { this.hideToast(true); } }, _handle_close_button_click: function _handle_close_button_click(event) { event.stopPropagation(); this.hideToast(true); }, _handle_remove: function _handle_remove() { this.props.handleRemove(this.props.toastId); }, _render_close_button: function _render_close_button() { return this.props.closeButton ? _react2.default.createElement("button", { className: "toast-close-button", role: "button", onClick: this._handle_close_button_click, dangerouslySetInnerHTML: { __html: "&times;" } }) : false; }, _render_title_element: function _render_title_element() { return this.props.title ? _react2.default.createElement( "div", { className: this.props.titleClassName }, this.props.title ) : false; }, _render_message_element: function _render_message_element() { return this.props.message ? _react2.default.createElement( "div", { className: this.props.messageClassName }, this.props.message ) : false; }, render: function render() { var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type]; return _react2.default.createElement( "div", { className: (0, _classnames2.default)(this.props.className, iconClassName), style: this.props.style, onClick: this.handleOnClick, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, this._render_close_button(), this._render_title_element(), this._render_message_element() ); } }; var animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, { displayName: { $set: "ToastMessage.animation" }, mixins: { $set: [_animationMixin2.default] } })); var jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, { displayName: { $set: "ToastMessage.jQuery" }, mixins: { $set: [_jQueryMixin2.default] } })); /* * assign default noop functions */ ToastMessageSpec.handleMouseEnter = noop; ToastMessageSpec.handleMouseLeave = noop; ToastMessageSpec.hideToast = noop; var ToastMessage = _react2.default.createClass(ToastMessageSpec); ToastMessage.animation = animation; ToastMessage.jQuery = jQuery; exports.default = ToastMessage; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _ReactTransitionEvents = __webpack_require__(25); var _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents); var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); var _elementClass = __webpack_require__(28); var _elementClass2 = _interopRequireDefault(_elementClass); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TICK = 17; var toString = Object.prototype.toString; exports.default = { getDefaultProps: function getDefaultProps() { return { transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate) showAnimation: "animated bounceIn", // or other animations from animate.css hideAnimation: "animated bounceOut", timeOut: 5000, extendedTimeOut: 1000 }; }, componentWillMount: function componentWillMount() { this.classNameQueue = []; this.isHiding = false; this.intervalId = null; }, componentDidMount: function componentDidMount() { var _this = this; this._is_mounted = true; this._show(); var node = _reactDom2.default.findDOMNode(this); var onHideComplete = function onHideComplete() { if (_this.isHiding) { _this._set_is_hiding(false); _ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete); _this._handle_remove(); } }; _ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete); if (this.props.timeOut > 0) { this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut)); } }, componentWillUnmount: function componentWillUnmount() { this._is_mounted = false; if (this.intervalId) { clearTimeout(this.intervalId); } }, _set_transition: function _set_transition(hide) { var animationType = hide ? "leave" : "enter"; var node = _reactDom2.default.findDOMNode(this); var className = this.props.transition + "-" + animationType; var activeClassName = className + "-active"; var endListener = function endListener(e) { if (e && e.target !== node) { return; } var classList = (0, _elementClass2.default)(node); classList.remove(className); classList.remove(activeClassName); _ReactTransitionEvents2.default.removeEndEventListener(node, endListener); }; _ReactTransitionEvents2.default.addEndEventListener(node, endListener); (0, _elementClass2.default)(node).add(className); // Need to do this to actually trigger a transition. this._queue_class(activeClassName); }, _clear_transition: function _clear_transition(hide) { var node = _reactDom2.default.findDOMNode(this); var animationType = hide ? "leave" : "enter"; var className = this.props.transition + "-" + animationType; var activeClassName = className + "-active"; var classList = (0, _elementClass2.default)(node); classList.remove(className); classList.remove(activeClassName); }, _set_animation: function _set_animation(hide) { var node = _reactDom2.default.findDOMNode(this); var animations = this._get_animation_classes(hide); var endListener = function endListener(e) { if (e && e.target !== node) { return; } animations.forEach(function (anim) { return (0, _elementClass2.default)(node).remove(anim); }); _ReactTransitionEvents2.default.removeEndEventListener(node, endListener); }; _ReactTransitionEvents2.default.addEndEventListener(node, endListener); animations.forEach(function (anim) { return (0, _elementClass2.default)(node).add(anim); }); }, _get_animation_classes: function _get_animation_classes(hide) { var animations = hide ? this.props.hideAnimation : this.props.showAnimation; if ("[object Array]" === toString.call(animations)) { return animations; } else if ("string" === typeof animations) { return animations.split(" "); } }, _clear_animation: function _clear_animation(hide) { var node = _reactDom2.default.findDOMNode(this); var animations = this._get_animation_classes(hide); animations.forEach(function (animation) { return (0, _elementClass2.default)(node).remove(animation); }); }, _queue_class: function _queue_class(className) { this.classNameQueue.push(className); if (!this.timeout) { this.timeout = setTimeout(this._flush_class_name_queue, TICK); } }, _flush_class_name_queue: function _flush_class_name_queue() { var _this2 = this; if (this._is_mounted) { (function () { var node = _reactDom2.default.findDOMNode(_this2); _this2.classNameQueue.forEach(function (className) { return (0, _elementClass2.default)(node).add(className); }); })(); } this.classNameQueue.length = 0; this.timeout = null; }, _show: function _show() { if (this.props.transition) { this._set_transition(); } else if (this.props.showAnimation) { this._set_animation(); } }, handleMouseEnter: function handleMouseEnter() { clearTimeout(this.intervalId); this._set_interval_id(null); if (this.isHiding) { this._set_is_hiding(false); if (this.props.hideAnimation) { this._clear_animation(true); } else if (this.props.transition) { this._clear_transition(true); } } }, handleMouseLeave: function handleMouseLeave() { if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) { this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut)); } }, hideToast: function hideToast(override) { if (this.isHiding || this.intervalId === null && !override) { return; } this._set_is_hiding(true); if (this.props.transition) { this._set_transition(true); } else if (this.props.hideAnimation) { this._set_animation(true); } else { this._handle_remove(); } }, _set_interval_id: function _set_interval_id(intervalId) { this.intervalId = intervalId; }, _set_is_hiding: function _set_is_hiding(isHiding) { this.isHiding = isHiding; } }; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ 'use strict'; var ExecutionEnvironment = __webpack_require__(26); var getVendorPrefixedEventName = __webpack_require__(27); 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; /***/ }, /* 26 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getVendorPrefixedEventName */ 'use strict'; var ExecutionEnvironment = __webpack_require__(26); /** * 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; /***/ }, /* 28 */ /***/ function(module, exports) { module.exports = function(opts) { return new ElementClass(opts) } function indexOf(arr, prop) { if (arr.indexOf) return arr.indexOf(prop) for (var i = 0, len = arr.length; i < len; i++) if (arr[i] === prop) return i return -1 } function ElementClass(opts) { if (!(this instanceof ElementClass)) return new ElementClass(opts) var self = this if (!opts) opts = {} // similar doing instanceof HTMLElement but works in IE8 if (opts.nodeType) opts = {el: opts} this.opts = opts this.el = opts.el || document.body if (typeof this.el !== 'object') this.el = document.querySelector(this.el) } ElementClass.prototype.add = function(className) { var el = this.el if (!el) return if (el.className === "") return el.className = className var classes = el.className.split(' ') if (indexOf(classes, className) > -1) return classes classes.push(className) el.className = classes.join(' ') return classes } ElementClass.prototype.remove = function(className) { var el = this.el if (!el) return if (el.className === "") return var classes = el.className.split(' ') var idx = indexOf(classes, className) if (idx > -1) classes.splice(idx, 1) el.className = classes.join(' ') return classes } ElementClass.prototype.has = function(className) { var el = this.el if (!el) return var classes = el.className.split(' ') return indexOf(classes, className) > -1 } ElementClass.prototype.toggle = function(className) { var el = this.el if (!el) return if (this.has(className)) this.remove(className) else this.add(className) } /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _reactDom = __webpack_require__(6); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function call_show_method($node, props) { $node[props.showMethod]({ duration: props.showDuration, easing: props.showEasing }); } exports.default = { getDefaultProps: function getDefaultProps() { return { style: { display: "none" }, // effective $.hide() showMethod: "fadeIn", // slideDown, and show are built into jQuery showDuration: 300, showEasing: "swing", // and linear are built into jQuery hideMethod: "fadeOut", hideDuration: 1000, hideEasing: "swing", // timeOut: 5000, extendedTimeOut: 1000 }; }, getInitialState: function getInitialState() { return { intervalId: null, isHiding: false }; }, componentDidMount: function componentDidMount() { call_show_method(this._get_$_node(), this.props); if (this.props.timeOut > 0) { this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut)); } }, handleMouseEnter: function handleMouseEnter() { clearTimeout(this.state.intervalId); this._set_interval_id(null); this._set_is_hiding(false); call_show_method(this._get_$_node().stop(true, true), this.props); }, handleMouseLeave: function handleMouseLeave() { if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) { this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut)); } }, hideToast: function hideToast(override) { if (this.state.isHiding || this.state.intervalId === null && !override) { return; } this.setState({ isHiding: true }); this._get_$_node()[this.props.hideMethod]({ duration: this.props.hideDuration, easing: this.props.hideEasing, complete: this._handle_remove }); }, _get_$_node: function _get_$_node() { /* eslint-disable no-undef */ return jQuery(_reactDom2.default.findDOMNode(this)); /* eslint-enable no-undef */ }, _set_interval_id: function _set_interval_id(intervalId) { this.setState({ intervalId: intervalId }); }, _set_is_hiding: function _set_is_hiding(isHiding) { this.setState({ isHiding: isHiding }); } }; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(global, module) {/** * @license * lodash <https://lodash.com/> * Copyright jQuery Foundation and other contributors <https://jquery.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.15.0'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, CURRY_RIGHT_FLAG = 16, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64, ARY_FLAG = 128, REARG_FLAG = 256, FLIP_FLAG = 512; /** Used to compose bitmasks for comparison styles. */ var UNORDERED_COMPARE_FLAG = 1, PARTIAL_COMPARE_FLAG = 2; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 150, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', ARY_FLAG], ['bind', BIND_FLAG], ['bindKey', BIND_KEY_FLAG], ['curry', CURRY_FLAG], ['curryRight', CURRY_RIGHT_FLAG], ['flip', FLIP_FLAG], ['partial', PARTIAL_FLAG], ['partialRight', PARTIAL_RIGHT_FLAG], ['rearg', REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', promiseTag = '[object Promise]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, reUnescapedHtml = /[&<>"'`]/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect hexadecimal string values. */ var reHasHexPrefix = /^0x/i; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23', rsComboSymbolsRange = '\\u20d0-\\u20f0', rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsLowerMisc = '(?:' + rsLower + '|' + rsMisc + ')', rsUpperMisc = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptLowerContr = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptUpperContr = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptLowerContr + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsUpperMisc + '+' + rsOptUpperContr + '(?=' + [rsBreak, rsUpper + rsLowerMisc, '$'].join('|') + ')', rsUpper + '?' + rsLowerMisc + '+' + rsOptLowerContr, rsUpper + '+' + rsOptUpperContr, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 'ss' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '`': '&#96;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'", '&#96;': '`' }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array ? array.length : 0; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array ? array.length : 0; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array ? array.length : 0, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array ? array.length : 0; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array ? array.length : 0, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array ? array.length : 0; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array ? array.length : 0; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array ? array.length : 0; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { if (value !== value) { return baseFindIndex(array, baseIsNaN, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array ? array.length : 0; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a cache value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { result++; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ function isHostObject(value) { // Many host objects are `Object` objects that can coerce to strings // despite having improperly defined `toString` methods. var result = false; if (value != null && typeof value.toString != 'function') { try { result = !!(value + ''); } catch (e) {} } return result; } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { result++; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Use `context` to stub `Date#getTime` use in `_.now`. * var stubbed = _.runInContext({ * 'Date': function() { * return { 'getTime': stubGetTime }; * } * }); * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ function runInContext(context) { context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, getPrototype = overArg(Object.getPrototypeOf, Object), iteratorSymbol = Symbol ? Symbol.iterator : undefined, objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /* Used to set `toString` methods. */ var defineProperty = (function() { var func = getNative(Object, 'defineProperty'), name = getNative.name; return (name && name.length > 2) ? func : undefined; }()); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */ var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf'); /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array of at least `200` elements * and any iteratees accept only one argument. The heuristic for whether a * section qualifies for shortcut fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB). Change the following template settings to use * alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { return this.has(key) && delete this.__data__[key]; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries ? entries.length : 0; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { return getMapData(this, key)['delete'](key); } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { getMapData(this, key).set(key, value); return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values ? values.length : 0; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { this.__data__ = new ListCache(entries); } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { return this.__data__['delete'](key); } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var cache = this.__data__; if (cache instanceof ListCache) { var pairs = cache.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); return this; } cache = this.__data__ = new MapCache(pairs); } cache.set(key, value); return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. // Safari 9 makes `arguments.length` enumerable in strict mode. var result = (isArray(value) || isArguments(value)) ? baseTimes(value.length, String) : []; var length = result.length, skipIndexes = !!length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) { result.push(key); } } return result; } /** * Used by `_.defaults` to customize its `_.assignIn` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function assignInDefaults(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (typeof key == 'number' && value === undefined && !(key in object))) { object[key] = value; } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { object[key] = value; } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths of elements to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, isNil = object == null, length = paths.length, result = Array(length); while (++index < length) { result[index] = isNil ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep] Specify a deep clone. * @param {boolean} [isFull] Specify a clone including symbols. * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, isFull, customizer, key, object, stack) { var result; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { if (isHostObject(value)) { return object ? value : {}; } result = initCloneObject(isFunc ? {} : value); if (!isDeep) { return copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (!isArr) { var props = isFull ? getAllKeys(value) : keys(value); } arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ function baseCreate(proto) { return isObject(proto) ? objectCreate(proto) : {}; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = isKey(path, object) ? [path] : castPath(path); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { return objectToString.call(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { if (!isKey(path, object)) { path = castPath(path); object = parent(object, path); path = last(path); } var func = object == null ? object : object[toKey(path)]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && objectToString.call(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && objectToString.call(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @param {boolean} [bitmask] The bitmask of comparison flags. * The bitmask may be composed of the following flags: * 1 - Unordered comparison * 2 - Partial comparison * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, bitmask, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparisons. * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack); } if (!(bitmask & PARTIAL_COMPARE_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, equalFunc, customizer, bitmask, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObject(value) && objectToString.call(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } if (!(isArray(source) || isTypedArray(source))) { var props = baseKeysIn(source); } arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { newValue = srcValue; if (isArray(srcValue) || isTypedArray(srcValue)) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else { isCommon = false; newValue = baseClone(srcValue, true); } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { isCommon = false; newValue = baseClone(srcValue, true); } else { newValue = objValue; } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} props The property identifiers to pick. * @returns {Object} Returns the new object. */ function basePick(object, props) { object = Object(object); return basePickBy(object, props, function(value, key) { return key in object; }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} props The property identifiers to pick from. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, props, predicate) { var index = -1, length = props.length, result = {}; while (++index < length) { var key = props[index], value = object[key]; if (predicate(value, key)) { result[key] = value; } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else if (!isKey(index, array)) { var path = castPath(index), object = parent(array, path); if (object != null) { delete object[toKey(last(path))]; } } else { delete array[toKey(index)]; } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = array; return apply(func, this, otherArgs); }; } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = isKey(path, object) ? [path] : castPath(path); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop detection. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = isKey(path, object) ? [path] : castPath(path); object = parent(object, path); var key = toKey(last(path)); return !(object != null && hasOwnProperty.call(object, key)) || delete object[key]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var index = -1, length = arrays.length; while (++index < length) { var result = result ? arrayPush( baseDifference(result, arrays[index], iteratee, comparator), baseDifference(arrays[index], result, iteratee, comparator) ) : arrays[index]; } return (result && result.length) ? baseUniq(result, iteratee, comparator) : []; } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @returns {Array} Returns the cast property path array. */ function castPath(value) { return isArray(value) ? value : stringToPath(value); } /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var result = new buffer.constructor(buffer.length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; assignValue(object, key, newValue === undefined ? source[key] : newValue); } return object; } /** * Copies own symbol properties of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return baseRest(function(funcs) { funcs = baseFlatten(funcs, 1); var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & ARY_FLAG, isBind = bitmask & BIND_FLAG, isBindKey = bitmask & BIND_KEY_FLAG, isCurried = bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG), isFlip = bitmask & FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return baseRest(function(iteratees) { iteratees = (iteratees.length == 1 && isArray(iteratees[0])) ? arrayMap(iteratees[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(iteratees, 1), baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); if (!(bitmask & CURRY_BOUND_FLAG)) { bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = nativeMin(toInteger(precision), 292); if (precision) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] == null ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (CURRY_FLAG | CURRY_RIGHT_FLAG)) { bitmask &= ~(CURRY_FLAG | CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == CURRY_FLAG || bitmask == CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & UNORDERED_COMPARE_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) { return seen.add(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & PARTIAL_COMPARE_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= UNORDERED_COMPARE_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} customizer The function to customize comparisons. * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual` * for more details. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, bitmask, stack) { var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * Creates an array of the own enumerable symbol properties of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray; /** * Creates an array of the own and inherited enumerable symbol properties * of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11, // for data views in Edge < 14, and promises in Node.js. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : undefined; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = isKey(path, object) ? [path] : castPath(path); var result, index = -1, length = path.length; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result) { return result; } var length = object ? object.length : 0; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length, lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (BIND_FLAG | BIND_KEY_FLAG | ARY_FLAG); var isCombo = ((srcBitmask == ARY_FLAG) && (bitmask == CURRY_FLAG)) || ((srcBitmask == ARY_FLAG) && (bitmask == REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (ARY_FLAG | REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & BIND_FLAG ? 0 : CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function mergeDefaults(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, mergeDefaults, stack); stack['delete'](srcValue); } return objValue; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = (function() { var count = 0, lastCalled = 0; return function(key, value) { var stamp = now(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return key; } } else { count = 0; } return baseSetData(key, value); }; }()); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ var setWrapToString = !defineProperty ? identity : function(wrapper, reference, bitmask) { var source = (reference + ''); return defineProperty(wrapper, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))) }); }; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoize(function(string) { string = toString(string); var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to process. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array ? array.length : 0; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length, args = Array(length ? length - 1 : 0), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return length ? arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)) : []; } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order of result values is determined by the * order they occur in the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. Result values are chosen from the first array. * The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. Result values * are chosen from the first array. The comparator is invoked with two arguments: * (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array ? array.length : 0; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array ? array.length : 0; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs ? pairs.length : 0, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array ? array.length : 0; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order of result values is determined by the * order they occur in the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. Result values are chosen from the first array. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. Result values are chosen * from the first array. The comparator is invoked with two arguments: * (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (comparator === last(mapped)) { comparator = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array ? nativeJoin.call(array, separator) : ''; } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = ( index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1) ) + 1; } if (value !== value) { return baseFindIndex(array, baseIsNaN, index - 1, true); } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = baseRest(function(array, indexes) { indexes = baseFlatten(indexes, 1); var length = array ? array.length : 0, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array ? nativeReverse.call(array) : array; } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] * The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array ? array.length : 0; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] * The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array ? array.length : 0; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array ? array.length : 0; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array ? array.length : 0; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false}, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); if (isArrayLikeObject(comparator)) { comparator = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each * element is kept. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The comparator is invoked with * two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] * The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The comparator is invoked with * two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); if (isArrayLikeObject(comparator)) { comparator = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths of elements to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = baseRest(function(paths) { paths = baseFlatten(paths, 1); var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] * The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] * The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] * The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] * The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _([1, 2]).forEach(function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] * The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { result[key] = [value]; } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', isProp = isKey(path), result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined); result[++index] = func ? apply(func, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] * The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { result[key] = value; }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var array = isArrayLike(collection) ? collection : values(collection), length = array.length; return length > 0 ? array[baseRandom(0, length - 1)] : undefined; } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { var index = -1, result = toArray(collection), length = result.length, lastIndex = length - 1; if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = baseClamp(toInteger(n), 0, length); } while (++index < n) { var rand = baseRandom(index, lastIndex), value = result[rand]; result[rand] = result[index]; result[index] = value; } result.length = n; return result; } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { return sampleSize(collection, MAX_ARRAY_LENGTH); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, function(o) { return o.user; }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] * * _.sortBy(users, 'user', function(o) { * return Math.floor(o.age / 10); * }); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = BIND_FLAG | BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, result = wait - timeSinceLastCall; return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one or more milliseconds. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result); return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Assign cache to `_.memoize`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = baseRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = baseRest(function(func, indexes) { return createWrap(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes, 1)); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { wrapper = wrapper == null ? identity : wrapper; return partial(wrapper, value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, false, true); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { return baseClone(value, false, true, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, true, true); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { return baseClone(value, true, true, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { // Safari 8.1 makes `arguments.callee` enumerable in strict mode. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); } /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && objectToString.call(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (nonEnumShadows || isPrototype(value)) { return !nativeKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are **not** supported. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } return (objectToString.call(value) == errorTag) || (typeof value.message == 'string' && typeof value.name == 'string'); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return !!value && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return !!value && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error('This method is not supported with core-js. Try https://github.com/es-shims.'); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && objectToString.call(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return (typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && objectToString.call(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && objectToString.call(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (iteratorSymbol && value[iteratorSymbol]) { return iteratorToArray(value[iteratorSymbol]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {string} Returns the string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths of elements to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = baseRest(function(object, paths) { return baseAt(object, baseFlatten(paths, 1)); }); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties ? baseAssign(result, properties) : result; } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(args) { args.push(undefined, assignInDefaults); return apply(assignInWith, undefined, args); }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, mergeDefaults); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { result[iteratee(value, key, object)] = value; }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { result[key] = iteratee(value, key, object); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with seven arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable string keyed properties of `object` that are * not omitted. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property identifiers to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = baseRest(function(object, props) { if (object == null) { return {}; } props = arrayMap(baseFlatten(props, 1), toKey); return basePick(object, baseDifference(getAllKeysIn(object), props)); }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [props] The property identifiers to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = baseRest(function(object, props) { return object == null ? {} : basePick(object, arrayMap(baseFlatten(props, 1), toKey)); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { return object == null ? {} : basePickBy(object, getAllKeysIn(object), getIteratee(predicate)); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = isKey(path, object) ? [path] : castPath(path); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { object = undefined; length = 1; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { if (isArr || isObject(object)) { var Ctor = object.constructor; if (isArr) { accumulator = isArray(object) ? new Ctor : []; } else { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } } else { accumulator = {}; } } (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object ? baseValues(object, keys(object)) : []; } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', "'", and "\`" in `string` to * their corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * Backticks are escaped because in IE < 9, they can break out of * attribute values or HTML comments. See [#59](https://html5sec.org/#59), * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and * [#133](https://html5sec.org/#133) of the * [HTML5 Security Cheatsheet](https://html5sec.org/) for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { // Chrome fails to trim leading <BOM> whitespace characters. // See https://bugs.chromium.org/p/v8/issues/detail?id=3109 for more details. if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } string = toString(string).replace(reTrim, ''); return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES delimiter as an alternative to the default "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, assignInDefaults); var imports = assignInWith({}, options.imports, settings.imports, assignInDefaults), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. var sourceURL = '//# sourceURL=' + ('sourceURL' in options ? options.sourceURL : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimEnd, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = baseRest(function(object, methodNames) { arrayEach(baseFlatten(methodNames, 1), function(key) { key = toKey(key); object[key] = bind(object[key], object); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs ? pairs.length : 0, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, true)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return (value == null || value !== value) ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, true)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, true)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, true)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(value)); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { var filtered = this.__filtered__; if (filtered && !index) { return new LazyWrapper(this); } n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = this.clone(); if (filtered) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = (lodashFunc.name + ''), names = realNames[key] || (realNames[key] = []); names.push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (iteratorSymbol) { lodash.prototype[iteratorSymbol] = wrapperToIterator; } return lodash; } /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (true) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return _; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // Check for `exports` after `define` in case a build optimizer adds it. else if (freeModule) { // Export for Node.js. (freeModule.exports = _)._ = _; // Export for CommonJS support. freeExports._ = _; } else { // Export to the global object. root._ = _; } }.call(this)); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(31)(module))) /***/ }, /* 31 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _PageButtonJs = __webpack_require__(33); var _PageButtonJs2 = _interopRequireDefault(_PageButtonJs); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var PaginationList = (function (_Component) { _inherits(PaginationList, _Component); function PaginationList() { var _this = this; _classCallCheck(this, PaginationList); _get(Object.getPrototypeOf(PaginationList.prototype), 'constructor', this).apply(this, arguments); this.changePage = function (page) { var _props = _this.props; var pageStartIndex = _props.pageStartIndex; var prePage = _props.prePage; var currPage = _props.currPage; var nextPage = _props.nextPage; var lastPage = _props.lastPage; var firstPage = _props.firstPage; var sizePerPage = _props.sizePerPage; if (page === prePage) { page = currPage - 1 < pageStartIndex ? pageStartIndex : currPage - 1; } else if (page === nextPage) { page = currPage + 1 > _this.lastPage ? _this.lastPage : currPage + 1; } else if (page === lastPage) { page = _this.lastPage; } else if (page === firstPage) { page = pageStartIndex; } else { page = parseInt(page, 10); } if (page !== currPage) { _this.props.changePage(page, sizePerPage); } }; this.changeSizePerPage = function (e) { e.preventDefault(); var selectSize = parseInt(e.currentTarget.getAttribute('data-page'), 10); var currPage = _this.props.currPage; if (selectSize !== _this.props.sizePerPage) { _this.totalPages = Math.ceil(_this.props.dataSize / selectSize); _this.lastPage = _this.props.pageStartIndex + _this.totalPages - 1; if (currPage > _this.lastPage) currPage = _this.lastPage; _this.props.changePage(currPage, selectSize); if (_this.props.onSizePerPageList) { _this.props.onSizePerPageList(selectSize); } } }; } _createClass(PaginationList, [{ key: 'render', value: function render() { var _this2 = this; var _props2 = this.props; var currPage = _props2.currPage; var dataSize = _props2.dataSize; var sizePerPage = _props2.sizePerPage; var sizePerPageList = _props2.sizePerPageList; var paginationShowsTotal = _props2.paginationShowsTotal; var pageStartIndex = _props2.pageStartIndex; var hideSizePerPage = _props2.hideSizePerPage; this.totalPages = Math.ceil(dataSize / sizePerPage); this.lastPage = this.props.pageStartIndex + this.totalPages - 1; var pageBtns = this.makePage(); var pageListStyle = { float: 'right', // override the margin-top defined in .pagination class in bootstrap. marginTop: '0px' }; var sizePerPageOptions = sizePerPageList.map(function (_sizePerPage) { var pageText = _sizePerPage.text || _sizePerPage; var pageNum = _sizePerPage.value || _sizePerPage; return _react2['default'].createElement( 'li', { key: pageText, role: 'presentation' }, _react2['default'].createElement( 'a', { role: 'menuitem', tabIndex: '-1', href: '#', 'data-page': pageNum, onClick: _this2.changeSizePerPage }, pageText ) ); }); var offset = Math.abs(_Const2['default'].PAGE_START_INDEX - pageStartIndex); var start = (currPage - pageStartIndex) * sizePerPage; start = dataSize === 0 ? 0 : start + 1; var to = Math.min(sizePerPage * (currPage + offset) - 1, dataSize); if (to >= dataSize) to--; var total = paginationShowsTotal ? _react2['default'].createElement( 'span', null, 'Showing rows ', start, ' to ', to + 1, ' of ', dataSize ) : null; if (typeof paginationShowsTotal === 'function') { total = paginationShowsTotal(start, to, dataSize); } var dropDownStyle = { visibility: hideSizePerPage ? 'hidden' : 'visible' }; return _react2['default'].createElement( 'div', { className: 'row', style: { marginTop: 15 } }, sizePerPageList.length > 1 ? _react2['default'].createElement( 'div', null, _react2['default'].createElement( 'div', { className: 'col-md-6' }, total, ' ', _react2['default'].createElement( 'span', { className: 'dropdown', style: dropDownStyle }, _react2['default'].createElement( 'button', { className: 'btn btn-default dropdown-toggle', type: 'button', id: 'pageDropDown', 'data-toggle': 'dropdown', 'aria-expanded': 'true' }, sizePerPage, _react2['default'].createElement( 'span', null, ' ', _react2['default'].createElement('span', { className: 'caret' }) ) ), _react2['default'].createElement( 'ul', { className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' }, sizePerPageOptions ) ) ), _react2['default'].createElement( 'div', { className: 'col-md-6' }, _react2['default'].createElement( 'ul', { className: 'pagination', style: pageListStyle }, pageBtns ) ) ) : _react2['default'].createElement( 'div', null, _react2['default'].createElement( 'div', { className: 'col-md-6' }, total ), _react2['default'].createElement( 'div', { className: 'col-md-6' }, _react2['default'].createElement( 'ul', { className: 'pagination', style: pageListStyle }, pageBtns ) ) ) ); } }, { key: 'makePage', value: function makePage() { var pages = this.getPages(); return pages.map(function (page) { var isActive = page === this.props.currPage; var disabled = false; var hidden = false; if (this.props.currPage === this.props.pageStartIndex && (page === this.props.firstPage || page === this.props.prePage)) { disabled = true; hidden = true; } if (this.props.currPage === this.lastPage && (page === this.props.nextPage || page === this.props.lastPage)) { disabled = true; hidden = true; } return _react2['default'].createElement( _PageButtonJs2['default'], { key: page, changePage: this.changePage, active: isActive, disable: disabled, hidden: hidden }, page ); }, this); } }, { key: 'getPages', value: function getPages() { var pages = undefined; var endPage = this.totalPages; if (endPage <= 0) return []; var startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), this.props.pageStartIndex); endPage = startPage + this.props.paginationSize - 1; if (endPage > this.lastPage) { endPage = this.lastPage; startPage = endPage - this.props.paginationSize + 1; } if (startPage !== this.props.pageStartIndex && this.totalPages > this.props.paginationSize) { pages = [this.props.firstPage, this.props.prePage]; } else if (this.totalPages > 1) { pages = [this.props.prePage]; } else { pages = []; } for (var i = startPage; i <= endPage; i++) { if (i >= this.props.pageStartIndex) pages.push(i); } if (endPage < this.lastPage) { pages.push(this.props.nextPage); pages.push(this.props.lastPage); } else if (endPage === this.lastPage && this.props.currPage !== this.lastPage) { pages.push(this.props.nextPage); } return pages; } }]); return PaginationList; })(_react.Component); PaginationList.propTypes = { currPage: _react.PropTypes.number, sizePerPage: _react.PropTypes.number, dataSize: _react.PropTypes.number, changePage: _react.PropTypes.func, sizePerPageList: _react.PropTypes.array, paginationShowsTotal: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]), paginationSize: _react.PropTypes.number, remote: _react.PropTypes.bool, onSizePerPageList: _react.PropTypes.func, prePage: _react.PropTypes.string, pageStartIndex: _react.PropTypes.number, hideSizePerPage: _react.PropTypes.bool }; PaginationList.defaultProps = { sizePerPage: _Const2['default'].SIZE_PER_PAGE, pageStartIndex: _Const2['default'].PAGE_START_INDEX }; exports['default'] = PaginationList; module.exports = exports['default']; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var PageButton = (function (_Component) { _inherits(PageButton, _Component); function PageButton(props) { var _this = this; _classCallCheck(this, PageButton); _get(Object.getPrototypeOf(PageButton.prototype), 'constructor', this).call(this, props); this.pageBtnClick = function (e) { e.preventDefault(); _this.props.changePage(e.currentTarget.textContent); }; } _createClass(PageButton, [{ key: 'render', value: function render() { var classes = (0, _classnames2['default'])({ 'active': this.props.active, 'disabled': this.props.disable, 'hidden': this.props.hidden }); return _react2['default'].createElement( 'li', { className: classes }, _react2['default'].createElement( 'a', { href: '#', onClick: this.pageBtnClick }, this.props.children ) ); } }]); return PageButton; })(_react.Component); PageButton.propTypes = { changePage: _react.PropTypes.func, active: _react.PropTypes.bool, disable: _react.PropTypes.bool, hidden: _react.PropTypes.bool, children: _react.PropTypes.node }; exports['default'] = PageButton; module.exports = exports['default']; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _Editor = __webpack_require__(12); var _Editor2 = _interopRequireDefault(_Editor); var _NotificationJs = __webpack_require__(13); var _NotificationJs2 = _interopRequireDefault(_NotificationJs); var ToolBar = (function (_Component) { _inherits(ToolBar, _Component); _createClass(ToolBar, null, [{ key: 'modalSeq', value: 0, enumerable: true }]); function ToolBar(props) { var _this = this, _arguments2 = arguments; _classCallCheck(this, ToolBar); _get(Object.getPrototypeOf(ToolBar.prototype), 'constructor', this).call(this, props); this.handleSaveBtnClick = function () { var newObj = _this.checkAndParseForm(); if (!newObj) { // validate errors return; } var msg = _this.props.onAddRow(newObj); if (msg) { _this.refs.notifier.notice('error', msg, 'Pressed ESC can cancel'); _this.clearTimeout(); // shake form and hack prevent modal hide _this.setState({ shakeEditor: true, validateState: 'this is hack for prevent bootstrap modal hide' }); // clear animate class _this.timeouteClear = setTimeout(function () { _this.setState({ shakeEditor: false }); }, 300); } else { // reset state and hide modal hide _this.setState({ validateState: null, shakeEditor: false }, function () { document.querySelector('.modal-backdrop').click(); document.querySelector('.' + _this.modalClassName).click(); }); // reset form _this.refs.form.reset(); } }; this.handleShowOnlyToggle = function () { _this.setState({ showSelected: !_this.state.showSelected }); _this.props.onShowOnlySelected(); }; this.handleDropRowBtnClick = function () { _this.props.onDropRow(); }; this.handleDebounce = function (func, wait, immediate) { var timeout = undefined; return function () { var later = function later() { timeout = null; if (!immediate) { func.apply(_this, _arguments2); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait || 0); if (callNow) { func.appy(_this, _arguments2); } }; }; this.handleKeyUp = function (event) { event.persist(); _this.debounceCallback(event); }; this.handleExportCSV = function () { _this.props.onExportCSV(); }; this.handleClearBtnClick = function () { _this.refs.seachInput.value = ''; _this.props.onSearch(''); }; this.timeouteClear = 0; this.modalClassName; this.state = { isInsertRowTrigger: true, validateState: null, shakeEditor: false, showSelected: false }; } _createClass(ToolBar, [{ key: 'componentWillMount', value: function componentWillMount() { var _this2 = this; var delay = this.props.searchDelayTime ? this.props.searchDelayTime : 0; this.debounceCallback = this.handleDebounce(function () { _this2.props.onSearch(_this2.refs.seachInput.value); }, delay); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.clearTimeout(); } }, { key: 'clearTimeout', value: (function (_clearTimeout) { function clearTimeout() { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; })(function () { if (this.timeouteClear) { clearTimeout(this.timeouteClear); this.timeouteClear = 0; } }) // modified by iuculanop // BEGIN }, { key: 'checkAndParseForm', value: function checkAndParseForm() { var _this3 = this; var newObj = {}; var validateState = {}; var isValid = true; var checkVal = undefined; var responseType = undefined; var tempValue = undefined; this.props.columns.forEach(function (column, i) { if (column.autoValue) { // when you want same auto generate value and not allow edit, example ID field var time = new Date().getTime(); tempValue = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time; } else if (column.hiddenOnInsert) { tempValue = ''; } else { var dom = this.refs[column.field + i]; tempValue = dom.value; if (column.editable && column.editable.type === 'checkbox') { var values = tempValue.split(':'); tempValue = dom.checked ? values[0] : values[1]; } if (column.editable && column.editable.validator) { // process validate checkVal = column.editable.validator(tempValue); responseType = typeof checkVal; if (responseType !== 'object' && checkVal !== true) { this.refs.notifier.notice('error', 'Form validate errors, please checking!', 'Pressed ESC can cancel'); isValid = false; validateState[column.field] = checkVal; } else if (responseType === 'object' && checkVal.isValid !== true) { this.refs.notifier.notice(checkVal.notification.type, checkVal.notification.msg, checkVal.notification.title); isValid = false; validateState[column.field] = checkVal.notification.msg; } } } newObj[column.field] = tempValue; }, this); if (isValid) { return newObj; } else { this.clearTimeout(); // show error in form and shake it this.setState({ validateState: validateState, shakeEditor: true }); this.timeouteClear = setTimeout(function () { _this3.setState({ shakeEditor: false }); }, 300); return null; } } // END }, { key: 'handleCloseBtn', value: function handleCloseBtn() { this.refs.warning.style.display = 'none'; } }, { key: 'render', value: function render() { this.modalClassName = 'bs-table-modal-sm' + ToolBar.modalSeq++; var insertBtn = null; var deleteBtn = null; var exportCSV = null; var showSelectedOnlyBtn = null; if (this.props.enableInsert) { insertBtn = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-info react-bs-table-add-btn', 'data-toggle': 'modal', 'data-target': '.' + this.modalClassName }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-plus' }), ' ', this.props.insertText ); } if (this.props.enableDelete) { deleteBtn = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-warning react-bs-table-del-btn', 'data-toggle': 'tooltip', 'data-placement': 'right', title: 'Drop selected row', onClick: this.handleDropRowBtnClick }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-trash' }), ' ', this.props.deleteText ); } if (this.props.enableShowOnlySelected) { showSelectedOnlyBtn = _react2['default'].createElement( 'button', { type: 'button', onClick: this.handleShowOnlyToggle, className: 'btn btn-primary', 'data-toggle': 'button', 'aria-pressed': 'false' }, this.state.showSelected ? _Const2['default'].SHOW_ALL : _Const2['default'].SHOW_ONLY_SELECT ); } if (this.props.enableExportCSV) { exportCSV = _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-success hidden-print', onClick: this.handleExportCSV }, _react2['default'].createElement('i', { className: 'glyphicon glyphicon-export' }), this.props.exportCSVText ); } var searchTextInput = this.renderSearchPanel(); var modal = this.props.enableInsert ? this.renderInsertRowModal() : null; return _react2['default'].createElement( 'div', { className: 'row' }, _react2['default'].createElement( 'div', { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-8' }, _react2['default'].createElement( 'div', { className: 'btn-group btn-group-sm', role: 'group' }, exportCSV, insertBtn, deleteBtn, showSelectedOnlyBtn ) ), _react2['default'].createElement( 'div', { className: 'col-xs-12 col-sm-6 col-md-6 col-lg-4' }, searchTextInput ), _react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }), modal ); } }, { key: 'renderSearchPanel', value: function renderSearchPanel() { if (this.props.enableSearch) { var classNames = 'form-group form-group-sm react-bs-table-search-form'; var clearBtn = null; if (this.props.clearSearch) { clearBtn = _react2['default'].createElement( 'span', { className: 'input-group-btn' }, _react2['default'].createElement( 'button', { className: 'btn btn-default', type: 'button', onClick: this.handleClearBtnClick }, 'Clear' ) ); classNames += ' input-group input-group-sm'; } return _react2['default'].createElement( 'div', { className: classNames }, _react2['default'].createElement('input', { ref: 'seachInput', className: 'form-control', type: 'text', defaultValue: this.props.defaultSearch, placeholder: this.props.searchPlaceholder ? this.props.searchPlaceholder : 'Search', onKeyUp: this.handleKeyUp }), clearBtn ); } else { return null; } } }, { key: 'renderInsertRowModal', value: function renderInsertRowModal() { var _this4 = this; var validateState = this.state.validateState || {}; var shakeEditor = this.state.shakeEditor; var inputField = this.props.columns.map(function (column, i) { var editable = column.editable; var format = column.format; var field = column.field; var name = column.name; var autoValue = column.autoValue; var hiddenOnInsert = column.hiddenOnInsert; var attr = { ref: field + i, placeholder: editable.placeholder ? editable.placeholder : name }; if (autoValue || hiddenOnInsert) { // when you want same auto generate value // and not allow edit, for example ID field return null; } var error = validateState[field] ? _react2['default'].createElement( 'span', { className: 'help-block bg-danger' }, validateState[field] ) : null; // let editor = Editor(editable,attr,format); // if(editor.props.type && editor.props.type == 'checkbox'){ return _react2['default'].createElement( 'div', { className: 'form-group', key: field }, _react2['default'].createElement( 'label', null, name ), (0, _Editor2['default'])(editable, attr, format, '', undefined, _this4.props.ignoreEditable), error ); }); var modalClass = (0, _classnames2['default'])('modal', 'fade', this.modalClassName, { // hack prevent bootstrap modal hide by reRender 'in': shakeEditor || this.state.validateState }); var dialogClass = (0, _classnames2['default'])('modal-dialog', 'modal-sm', { 'animated': shakeEditor, 'shake': shakeEditor }); return _react2['default'].createElement( 'div', { ref: 'modal', className: modalClass, tabIndex: '-1', role: 'dialog' }, _react2['default'].createElement( 'div', { className: dialogClass }, _react2['default'].createElement( 'div', { className: 'modal-content' }, _react2['default'].createElement( 'div', { className: 'modal-header' }, _react2['default'].createElement( 'button', { type: 'button', className: 'close', 'data-dismiss': 'modal', 'aria-label': 'Close' }, _react2['default'].createElement( 'span', { 'aria-hidden': 'true' }, '×' ) ), _react2['default'].createElement( 'h4', { className: 'modal-title' }, 'New Record' ) ), _react2['default'].createElement( 'div', { className: 'modal-body' }, _react2['default'].createElement( 'form', { ref: 'form' }, inputField ) ), _react2['default'].createElement( 'div', { className: 'modal-footer' }, _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-default', 'data-dismiss': 'modal' }, this.props.closeText ), _react2['default'].createElement( 'button', { type: 'button', className: 'btn btn-primary', onClick: this.handleSaveBtnClick }, this.props.saveText ) ) ) ) ); } }]); return ToolBar; })(_react.Component); ToolBar.propTypes = { onAddRow: _react.PropTypes.func, onDropRow: _react.PropTypes.func, onShowOnlySelected: _react.PropTypes.func, enableInsert: _react.PropTypes.bool, enableDelete: _react.PropTypes.bool, enableSearch: _react.PropTypes.bool, enableShowOnlySelected: _react.PropTypes.bool, columns: _react.PropTypes.array, searchPlaceholder: _react.PropTypes.string, exportCSVText: _react.PropTypes.string, insertText: _react.PropTypes.string, deleteText: _react.PropTypes.string, saveText: _react.PropTypes.string, closeText: _react.PropTypes.string, clearSearch: _react.PropTypes.bool, ignoreEditable: _react.PropTypes.bool, defaultSearch: _react.PropTypes.string }; ToolBar.defaultProps = { enableInsert: false, enableDelete: false, enableSearch: false, enableShowOnlySelected: false, clearSearch: false, ignoreEditable: false, exportCSVText: _Const2['default'].EXPORT_CSV_TEXT, insertText: _Const2['default'].INSERT_BTN_TEXT, deleteText: _Const2['default'].DELETE_BTN_TEXT, saveText: _Const2['default'].SAVE_BTN_TEXT, closeText: _Const2['default'].CLOSE_BTN_TEXT }; exports['default'] = ToolBar; module.exports = exports['default']; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var TableFilter = (function (_Component) { _inherits(TableFilter, _Component); function TableFilter(props) { var _this = this; _classCallCheck(this, TableFilter); _get(Object.getPrototypeOf(TableFilter.prototype), 'constructor', this).call(this, props); this.handleKeyUp = function (e) { var _e$currentTarget = e.currentTarget; var value = _e$currentTarget.value; var name = _e$currentTarget.name; if (value.trim() === '') { delete _this.filterObj[name]; } else { _this.filterObj[name] = value; } _this.props.onFilter(_this.filterObj); }; this.filterObj = {}; } _createClass(TableFilter, [{ key: 'render', value: function render() { var _props = this.props; var striped = _props.striped; var condensed = _props.condensed; var rowSelectType = _props.rowSelectType; var columns = _props.columns; var tableClasses = (0, _classnames2['default'])('table', { 'table-striped': striped, 'table-condensed': condensed }); var selectRowHeader = null; if (rowSelectType === _Const2['default'].ROW_SELECT_SINGLE || rowSelectType === _Const2['default'].ROW_SELECT_MULTI) { var style = { width: 35, paddingLeft: 0, paddingRight: 0 }; selectRowHeader = _react2['default'].createElement( 'th', { style: style, key: -1 }, 'Filter' ); } var filterField = columns.map(function (column) { var hidden = column.hidden; var width = column.width; var name = column.name; var thStyle = { display: hidden ? 'none' : null, width: width }; return _react2['default'].createElement( 'th', { key: name, style: thStyle }, _react2['default'].createElement( 'div', { className: 'th-inner table-header-column' }, _react2['default'].createElement('input', { size: '10', type: 'text', placeholder: name, name: name, onKeyUp: this.handleKeyUp }) ) ); }, this); return _react2['default'].createElement( 'table', { className: tableClasses, style: { marginTop: 5 } }, _react2['default'].createElement( 'thead', null, _react2['default'].createElement( 'tr', { style: { borderBottomStyle: 'hidden' } }, selectRowHeader, filterField ) ) ); } }]); return TableFilter; })(_react.Component); TableFilter.propTypes = { columns: _react.PropTypes.array, rowSelectType: _react.PropTypes.string, onFilter: _react.PropTypes.func }; exports['default'] = TableFilter; module.exports = exports['default']; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /* eslint no-nested-ternary: 0 */ /* eslint guard-for-in: 0 */ /* eslint no-console: 0 */ /* eslint eqeqeq: 0 */ /* eslint one-var: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); function _sort(arr, sortField, order, sortFunc, sortFuncExtraData) { order = order.toLowerCase(); var isDesc = order === _Const2['default'].SORT_DESC; arr.sort(function (a, b) { if (sortFunc) { return sortFunc(a, b, order, sortField, sortFuncExtraData); } else { var valueA = a[sortField] === null ? '' : a[sortField]; var valueB = b[sortField] === null ? '' : b[sortField]; if (isDesc) { if (typeof valueB === 'string') { return valueB.localeCompare(valueA); } else { return valueA > valueB ? -1 : valueA < valueB ? 1 : 0; } } else { if (typeof valueA === 'string') { return valueA.localeCompare(valueB); } else { return valueA < valueB ? -1 : valueA > valueB ? 1 : 0; } } } }); return arr; } var TableDataStore = (function () { function TableDataStore(data) { _classCallCheck(this, TableDataStore); this.data = data; this.colInfos = null; this.filteredData = null; this.isOnFilter = false; this.filterObj = null; this.searchText = null; this.sortObj = null; this.pageObj = {}; this.selected = []; this.multiColumnSearch = false; this.showOnlySelected = false; this.remote = false; // remote data } _createClass(TableDataStore, [{ key: 'setProps', value: function setProps(props) { this.keyField = props.keyField; this.enablePagination = props.isPagination; this.colInfos = props.colInfos; this.remote = props.remote; this.multiColumnSearch = props.multiColumnSearch; } }, { key: 'setData', value: function setData(data) { this.data = data; if (this.remote) { return; } this._refresh(true); } }, { key: 'getColInfos', value: function getColInfos() { return this.colInfos; } }, { key: 'getSortInfo', value: function getSortInfo() { return this.sortObj; } }, { key: 'setSortInfo', value: function setSortInfo(order, sortField) { this.sortObj = { order: order, sortField: sortField }; } }, { key: 'setSelectedRowKey', value: function setSelectedRowKey(selectedRowKeys) { this.selected = selectedRowKeys; } }, { key: 'getRowByKey', value: function getRowByKey(keys) { var _this = this; return keys.map(function (key) { var result = _this.data.filter(function (d) { return d[_this.keyField] === key; }); if (result.length !== 0) return result[0]; }); } }, { key: 'getSelectedRowKeys', value: function getSelectedRowKeys() { return this.selected; } }, { key: 'getCurrentDisplayData', value: function getCurrentDisplayData() { if (this.isOnFilter) return this.filteredData;else return this.data; } }, { key: '_refresh', value: function _refresh(skipSorting) { if (this.isOnFilter) { if (this.filterObj !== null) this.filter(this.filterObj); if (this.searchText !== null) this.search(this.searchText); } if (!skipSorting && this.sortObj) { this.sort(this.sortObj.order, this.sortObj.sortField); } } }, { key: 'ignoreNonSelected', value: function ignoreNonSelected() { var _this2 = this; this.showOnlySelected = !this.showOnlySelected; if (this.showOnlySelected) { this.isOnFilter = true; this.filteredData = this.data.filter(function (row) { var result = _this2.selected.find(function (x) { return row[_this2.keyField] === x; }); return typeof result !== 'undefined' ? true : false; }); } else { this.isOnFilter = false; } } }, { key: 'sort', value: function sort(order, sortField) { this.setSortInfo(order, sortField); var currentDisplayData = this.getCurrentDisplayData(); if (!this.colInfos[sortField]) return this; var _colInfos$sortField = this.colInfos[sortField]; var sortFunc = _colInfos$sortField.sortFunc; var sortFuncExtraData = _colInfos$sortField.sortFuncExtraData; currentDisplayData = _sort(currentDisplayData, sortField, order, sortFunc, sortFuncExtraData); return this; } }, { key: 'page', value: function page(_page, sizePerPage) { this.pageObj.end = _page * sizePerPage - 1; this.pageObj.start = this.pageObj.end - (sizePerPage - 1); return this; } }, { key: 'edit', value: function edit(newVal, rowIndex, fieldName) { var currentDisplayData = this.getCurrentDisplayData(); var rowKeyCache = undefined; if (!this.enablePagination) { currentDisplayData[rowIndex][fieldName] = newVal; rowKeyCache = currentDisplayData[rowIndex][this.keyField]; } else { currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal; rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField]; } if (this.isOnFilter) { this.data.forEach(function (row) { if (row[this.keyField] === rowKeyCache) { row[fieldName] = newVal; } }, this); if (this.filterObj !== null) this.filter(this.filterObj); if (this.searchText !== null) this.search(this.searchText); } return this; } }, { key: 'addAtBegin', value: function addAtBegin(newObj) { if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') { throw this.keyField + ' can\'t be empty value.'; } var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData.forEach(function (row) { if (row[this.keyField].toString() === newObj[this.keyField].toString()) { throw this.keyField + ' ' + newObj[this.keyField] + ' already exists'; } }, this); currentDisplayData.unshift(newObj); if (this.isOnFilter) { this.data.unshift(newObj); } this._refresh(false); } }, { key: 'add', value: function add(newObj) { if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') { throw this.keyField + ' can\'t be empty value.'; } var currentDisplayData = this.getCurrentDisplayData(); currentDisplayData.forEach(function (row) { if (row[this.keyField].toString() === newObj[this.keyField].toString()) { throw this.keyField + ' ' + newObj[this.keyField] + ' already exists'; } }, this); currentDisplayData.push(newObj); if (this.isOnFilter) { this.data.push(newObj); } this._refresh(false); } }, { key: 'remove', value: function remove(rowKey) { var _this3 = this; var currentDisplayData = this.getCurrentDisplayData(); var result = currentDisplayData.filter(function (row) { return rowKey.indexOf(row[_this3.keyField]) === -1; }); if (this.isOnFilter) { this.data = this.data.filter(function (row) { return rowKey.indexOf(row[_this3.keyField]) === -1; }); this.filteredData = result; } else { this.data = result; } } }, { key: 'filter', value: function filter(filterObj) { if (Object.keys(filterObj).length === 0) { this.filteredData = null; this.isOnFilter = false; this.filterObj = null; if (this.searchText) this._search(this.data); } else { var source = this.data; this.filterObj = filterObj; if (this.searchText) { this._search(source); source = this.filteredData; } this._filter(source); } } }, { key: 'filterNumber', value: function filterNumber(targetVal, filterVal, comparator) { var valid = true; switch (comparator) { case '=': { if (targetVal != filterVal) { valid = false; } break; } case '>': { if (targetVal <= filterVal) { valid = false; } break; } case '>=': { if (targetVal < filterVal) { valid = false; } break; } case '<': { if (targetVal >= filterVal) { valid = false; } break; } case '<=': { if (targetVal > filterVal) { valid = false; } break; } case '!=': { if (targetVal == filterVal) { valid = false; } break; } default: { console.error('Number comparator provided is not supported'); break; } } return valid; } }, { key: 'filterDate', value: function filterDate(targetVal, filterVal, comparator) { // if (!targetVal) { // return false; // } // return (targetVal.getDate() === filterVal.getDate() && // targetVal.getMonth() === filterVal.getMonth() && // targetVal.getFullYear() === filterVal.getFullYear()); var valid = true; switch (comparator) { case '=': { if (targetVal != filterVal) { valid = false; } break; } case '>': { if (targetVal <= filterVal) { valid = false; } break; } case '>=': { if (targetVal < filterVal) { valid = false; } break; } case '<': { if (targetVal >= filterVal) { valid = false; } break; } case '<=': { if (targetVal > filterVal) { valid = false; } break; } case '!=': { if (targetVal == filterVal) { valid = false; } break; } default: { console.error('Date comparator provided is not supported'); break; } } return valid; } }, { key: 'filterRegex', value: function filterRegex(targetVal, filterVal) { try { return new RegExp(filterVal, 'i').test(targetVal); } catch (e) { return true; } } }, { key: 'filterCustom', value: function filterCustom(targetVal, filterVal, callbackInfo) { if (callbackInfo !== null && typeof callbackInfo === 'object') { return callbackInfo.callback(targetVal, callbackInfo.callbackParameters); } return this.filterText(targetVal, filterVal); } }, { key: 'filterText', value: function filterText(targetVal, filterVal) { targetVal = targetVal.toString().toLowerCase(); filterVal = filterVal.toString().toLowerCase(); if (targetVal.indexOf(filterVal) === -1) { return false; } return true; } /* General search function * It will search for the text if the input includes that text; */ }, { key: 'search', value: function search(searchText) { if (searchText.trim() === '') { this.filteredData = null; this.isOnFilter = false; this.searchText = null; if (this.filterObj) this._filter(this.data); } else { var source = this.data; this.searchText = searchText; if (this.filterObj) { this._filter(source); source = this.filteredData; } this._search(source); } } }, { key: '_filter', value: function _filter(source) { var _this4 = this; var filterObj = this.filterObj; this.filteredData = source.filter(function (row, r) { var valid = true; var filterVal = undefined; for (var key in filterObj) { var targetVal = row[key]; if (targetVal === null || targetVal === undefined) { targetVal = ''; } switch (filterObj[key].type) { case _Const2['default'].FILTER_TYPE.NUMBER: { filterVal = filterObj[key].value.number; break; } case _Const2['default'].FILTER_TYPE.CUSTOM: { filterVal = typeof filterObj[key].value === 'object' ? undefined : typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value; break; } case _Const2['default'].FILTER_TYPE.DATE: { filterVal = filterObj[key].value.date; break; } case _Const2['default'].FILTER_TYPE.REGEX: { filterVal = filterObj[key].value; break; } default: { filterVal = typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value; if (filterVal === undefined) { // Support old filter filterVal = filterObj[key].toLowerCase(); } break; } } var format = undefined, filterFormatted = undefined, formatExtraData = undefined, filterValue = undefined; if (_this4.colInfos[key]) { format = _this4.colInfos[key].format; filterFormatted = _this4.colInfos[key].filterFormatted; formatExtraData = _this4.colInfos[key].formatExtraData; filterValue = _this4.colInfos[key].filterValue; if (filterFormatted && format) { targetVal = format(row[key], row, formatExtraData, r); } else if (filterValue) { targetVal = filterValue(row[key], row); } } switch (filterObj[key].type) { case _Const2['default'].FILTER_TYPE.NUMBER: { valid = _this4.filterNumber(targetVal, filterVal, filterObj[key].value.comparator); break; } case _Const2['default'].FILTER_TYPE.DATE: { valid = _this4.filterDate(targetVal, filterVal, filterObj[key].value.comparator); break; } case _Const2['default'].FILTER_TYPE.REGEX: { valid = _this4.filterRegex(targetVal, filterVal); break; } case _Const2['default'].FILTER_TYPE.CUSTOM: { valid = _this4.filterCustom(targetVal, filterVal, filterObj[key].value); break; } default: { if (filterObj[key].type === _Const2['default'].FILTER_TYPE.SELECT && filterFormatted && filterFormatted && format) { filterVal = format(filterVal, row, formatExtraData, r); } valid = _this4.filterText(targetVal, filterVal); break; } } if (!valid) { break; } } return valid; }); this.isOnFilter = true; } }, { key: '_search', value: function _search(source) { var _this5 = this; var searchTextArray = []; if (this.multiColumnSearch) { searchTextArray = this.searchText.split(' '); } else { searchTextArray.push(this.searchText); } this.filteredData = source.filter(function (row, r) { var keys = Object.keys(row); var valid = false; // for loops are ugly, but performance matters here. // And you cant break from a forEach. // http://jsperf.com/for-vs-foreach/66 for (var i = 0, keysLength = keys.length; i < keysLength; i++) { var key = keys[i]; if (_this5.colInfos[key] && row[key]) { var _colInfos$key = _this5.colInfos[key]; var format = _colInfos$key.format; var filterFormatted = _colInfos$key.filterFormatted; var filterValue = _colInfos$key.filterValue; var formatExtraData = _colInfos$key.formatExtraData; var searchable = _colInfos$key.searchable; var targetVal = row[key]; if (searchable) { if (filterFormatted && format) { targetVal = format(targetVal, row, formatExtraData, r); } else if (filterValue) { targetVal = filterValue(targetVal, row); } for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) { var filterVal = searchTextArray[j].toLowerCase(); if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) { valid = true; break; } } } } } return valid; }); this.isOnFilter = true; } }, { key: 'getDataIgnoringPagination', value: function getDataIgnoringPagination() { return this.getCurrentDisplayData(); } }, { key: 'get', value: function get() { var _data = this.getCurrentDisplayData(); if (_data.length === 0) return _data; if (this.remote || !this.enablePagination) { return _data; } else { var result = []; for (var i = this.pageObj.start; i <= this.pageObj.end; i++) { result.push(_data[i]); if (i + 1 === _data.length) break; } return result; } } }, { key: 'getKeyField', value: function getKeyField() { return this.keyField; } }, { key: 'getDataNum', value: function getDataNum() { return this.getCurrentDisplayData().length; } }, { key: 'isChangedPage', value: function isChangedPage() { return this.pageObj.start && this.pageObj.end ? true : false; } }, { key: 'isEmpty', value: function isEmpty() { return this.data.length === 0 || this.data === null || this.data === undefined; } }, { key: 'getAllRowkey', value: function getAllRowkey() { var _this6 = this; return this.data.map(function (row) { return row[_this6.keyField]; }); } }]); return TableDataStore; })(); exports.TableDataStore = TableDataStore; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); exports['default'] = { renderReactSortCaret: function renderReactSortCaret(order) { var orderClass = (0, _classnames2['default'])('order', { 'dropup': order === _Const2['default'].SORT_ASC }); return _react2['default'].createElement( 'span', { className: orderClass }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 5px' } }) ); }, getScrollBarWidth: function getScrollBarWidth() { var inner = document.createElement('p'); inner.style.width = '100%'; inner.style.height = '200px'; var outer = document.createElement('div'); outer.style.position = 'absolute'; outer.style.top = '0px'; outer.style.left = '0px'; outer.style.visibility = 'hidden'; outer.style.width = '200px'; outer.style.height = '150px'; outer.style.overflow = 'hidden'; outer.appendChild(inner); document.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 === w2) w2 = outer.clientWidth; document.body.removeChild(outer); return w1 - w2; }, canUseDOM: function canUseDOM() { return typeof window !== 'undefined' && typeof window.document !== 'undefined'; } }; module.exports = exports['default']; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /* eslint block-scoped-var: 0 */ /* eslint vars-on-top: 0 */ /* eslint no-var: 0 */ /* eslint no-unused-vars: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _util = __webpack_require__(37); var _util2 = _interopRequireDefault(_util); if (_util2['default'].canUseDOM()) { var filesaver = __webpack_require__(39); var saveAs = filesaver.saveAs; } function toString(data, keys) { var dataString = ''; if (data.length === 0) return dataString; dataString += keys.map(function (x) { return x.header; }).join(',') + '\n'; data.map(function (row) { keys.map(function (col, i) { var field = col.field; var format = col.format; var value = typeof format !== 'undefined' ? format(row[field], row) : row[field]; var cell = typeof value !== 'undefined' ? '"' + value + '"' : ''; dataString += cell; if (i + 1 < keys.length) dataString += ','; }); dataString += '\n'; }); return dataString; } var exportCSV = function exportCSV(data, keys, filename) { var dataString = toString(data, keys); if (typeof window !== 'undefined') { saveAs(new Blob([dataString], { type: 'text/plain;charset=utf-8' }), filename, true); } }; exports['default'] = exportCSV; module.exports = exports['default']; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js * A saveAs() FileSaver implementation. * 1.1.20151003 * * By Eli Grey, http://eligrey.com * License: MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ "use strict"; var saveAs = saveAs || (function (view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document, // only get URL when necessary in case Blob.js hasn't overridden it yet get_URL = function get_URL() { return view.URL || view.webkitURL || view; }, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"), can_use_save_link = ("download" in save_link), click = function click(node) { var event = new MouseEvent("click"); node.dispatchEvent(event); }, is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent), webkit_req_fs = view.webkitRequestFileSystem, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem, throw_outside = function throw_outside(ex) { (view.setImmediate || view.setTimeout)(function () { throw ex; }, 0); }, force_saveable_type = "application/octet-stream", fs_min_size = 0, // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047 // for the reasoning behind the timeout and revocation flow arbitrary_revoke_timeout = 500, // in ms revoke = function revoke(file) { var revoker = function revoker() { if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } }; if (view.chrome) { revoker(); } else { setTimeout(revoker, arbitrary_revoke_timeout); } }, dispatch = function dispatch(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } }, auto_bom = function auto_bom(blob) { // prepend BOM for UTF-8 XML and text/* types (including HTML) if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { return new Blob(["", blob], { type: blob.type }); } return blob; }, FileSaver = function FileSaver(blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } // First try a.download, then web filesystem, then object URLs var filesaver = this, type = blob.type, blob_changed = false, object_url, target_view, dispatch_all = function dispatch_all() { dispatch(filesaver, "writestart progress write writeend".split(" ")); }, // on any filesys errors revert to saving with object URLs fs_error = function fs_error() { if (target_view && is_safari && typeof FileReader !== "undefined") { // Safari doesn't allow downloading of blob urls var reader = new FileReader(); reader.onloadend = function () { var base64Data = reader.result; target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/)); filesaver.readyState = filesaver.DONE; dispatch_all(); }; reader.readAsDataURL(blob); filesaver.readyState = filesaver.INIT; return; } // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_URL().createObjectURL(blob); } if (target_view) { target_view.location.href = object_url; } else { var new_tab = view.open(object_url, "_blank"); if (new_tab == undefined && is_safari) { //Apple do not allow window.open, see http://bit.ly/1kZffRI view.location.href = object_url; } } filesaver.readyState = filesaver.DONE; dispatch_all(); revoke(object_url); }, abortable = function abortable(func) { return function () { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; }, create_if_not_found = { create: true, exclusive: false }, slice; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_URL().createObjectURL(blob); save_link.href = object_url; save_link.download = name; setTimeout(function () { click(save_link); dispatch_all(); revoke(object_url); filesaver.readyState = filesaver.DONE; }); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 // Update: Google errantly closed 91158, I submitted it again: // https://code.google.com/p/chromium/issues/detail?id=389642 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) { var save = function save() { dir.getFile(name, create_if_not_found, abortable(function (file) { file.createWriter(abortable(function (writer) { writer.onwriteend = function (event) { target_view.location.href = file.toURL(); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); revoke(file); }; writer.onerror = function () { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function (event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function () { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, { create: false }, abortable(function (file) { // delete file if it already exists file.remove(); save(); }), abortable(function (ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); }, FS_proto = FileSaver.prototype, saveAs = function saveAs(blob, name, no_auto_bom) { return new FileSaver(blob, name, no_auto_bom); }; // IE 10+ (native saveAs) if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { return function (blob, name, no_auto_bom) { if (!no_auto_bom) { blob = auto_bom(blob); } return navigator.msSaveOrOpenBlob(blob, name || "download"); }; } FS_proto.abort = function () { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; return saveAs; })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined" && module.exports) { module.exports.saveAs = saveAs; } else if ("function" !== "undefined" && __webpack_require__(40) !== null && __webpack_require__(41) != null) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return saveAs; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 40 */ /***/ function(module, exports) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 41 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _events = __webpack_require__(43); var Filter = (function (_EventEmitter) { _inherits(Filter, _EventEmitter); function Filter(data) { _classCallCheck(this, Filter); _get(Object.getPrototypeOf(Filter.prototype), 'constructor', this).call(this, data); this.currentFilter = {}; } _createClass(Filter, [{ key: 'handleFilter', value: function handleFilter(dataField, value, type) { var filterType = type || _Const2['default'].FILTER_TYPE.CUSTOM; if (value !== null && typeof value === 'object') { // value of the filter is an object var hasValue = true; for (var prop in value) { if (!value[prop] || value[prop] === '') { hasValue = false; break; } } // if one of the object properties is undefined or empty, we remove the filter if (hasValue) { this.currentFilter[dataField] = { value: value, type: filterType }; } else { delete this.currentFilter[dataField]; } } else if (!value || value.trim() === '') { delete this.currentFilter[dataField]; } else { this.currentFilter[dataField] = { value: value.trim(), type: filterType }; } this.emit('onFilterChange', this.currentFilter); } }]); return Filter; })(_events.EventEmitter); exports.Filter = Filter; /***/ }, /* 43 */ /***/ function(module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /* eslint default-case: 0 */ /* eslint guard-for-in: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var _util = __webpack_require__(37); var _util2 = _interopRequireDefault(_util); var _filtersDate = __webpack_require__(45); var _filtersDate2 = _interopRequireDefault(_filtersDate); var _filtersText = __webpack_require__(46); var _filtersText2 = _interopRequireDefault(_filtersText); var _filtersRegex = __webpack_require__(47); var _filtersRegex2 = _interopRequireDefault(_filtersRegex); var _filtersSelect = __webpack_require__(48); var _filtersSelect2 = _interopRequireDefault(_filtersSelect); var _filtersNumber = __webpack_require__(49); var _filtersNumber2 = _interopRequireDefault(_filtersNumber); var TableHeaderColumn = (function (_Component) { _inherits(TableHeaderColumn, _Component); function TableHeaderColumn(props) { var _this = this; _classCallCheck(this, TableHeaderColumn); _get(Object.getPrototypeOf(TableHeaderColumn.prototype), 'constructor', this).call(this, props); this.handleColumnClick = function () { if (!_this.props.dataSort) return; var order = _this.props.sort === _Const2['default'].SORT_DESC ? _Const2['default'].SORT_ASC : _Const2['default'].SORT_DESC; _this.props.onSort(order, _this.props.dataField); }; this.handleFilter = this.handleFilter.bind(this); } _createClass(TableHeaderColumn, [{ key: 'handleFilter', value: function handleFilter(value, type) { this.props.filter.emitter.handleFilter(this.props.dataField, value, type); } }, { key: 'getFilters', value: function getFilters() { switch (this.props.filter.type) { case _Const2['default'].FILTER_TYPE.TEXT: { return _react2['default'].createElement(_filtersText2['default'], _extends({ ref: 'textFilter' }, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.REGEX: { return _react2['default'].createElement(_filtersRegex2['default'], _extends({ ref: 'regexFilter' }, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.SELECT: { return _react2['default'].createElement(_filtersSelect2['default'], _extends({ ref: 'selectFilter' }, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.NUMBER: { return _react2['default'].createElement(_filtersNumber2['default'], _extends({ ref: 'numberFilter' }, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.DATE: { return _react2['default'].createElement(_filtersDate2['default'], _extends({ ref: 'dateFilter' }, this.props.filter, { columnName: this.props.children, filterHandler: this.handleFilter })); } case _Const2['default'].FILTER_TYPE.CUSTOM: { return this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters); } } } }, { key: 'componentDidMount', value: function componentDidMount() { this.refs['header-col'].setAttribute('data-field', this.props.dataField); } }, { key: 'render', value: function render() { var defaultCaret = undefined; var _props = this.props; var dataAlign = _props.dataAlign; var headerAlign = _props.headerAlign; var hidden = _props.hidden; var sort = _props.sort; var dataSort = _props.dataSort; var sortIndicator = _props.sortIndicator; var children = _props.children; var caretRender = _props.caretRender; var thStyle = { textAlign: headerAlign || dataAlign, display: hidden ? 'none' : null }; if (sortIndicator) { defaultCaret = !dataSort ? null : _react2['default'].createElement( 'span', { className: 'order' }, _react2['default'].createElement( 'span', { className: 'dropdown' }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } }) ), _react2['default'].createElement( 'span', { className: 'dropup' }, _react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } }) ) ); } var sortCaret = sort ? _util2['default'].renderReactSortCaret(sort) : defaultCaret; if (caretRender) { sortCaret = caretRender(sort); } var classes = this.props.className + ' ' + (dataSort ? 'sort-column' : ''); var title = typeof children === 'string' ? { title: children } : null; return _react2['default'].createElement( 'th', _extends({ ref: 'header-col', className: classes, style: thStyle, onClick: this.handleColumnClick }, title), children, sortCaret, _react2['default'].createElement( 'div', { onClick: function (e) { return e.stopPropagation(); } }, this.props.filter ? this.getFilters() : null ) ); } }, { key: 'cleanFiltered', value: function cleanFiltered() { if (this.props.filter === undefined) { return; } switch (this.props.filter.type) { case _Const2['default'].FILTER_TYPE.TEXT: { this.refs.textFilter.cleanFiltered(); break; } case _Const2['default'].FILTER_TYPE.REGEX: { this.refs.regexFilter.cleanFiltered(); break; } case _Const2['default'].FILTER_TYPE.SELECT: { this.refs.selectFilter.cleanFiltered(); break; } case _Const2['default'].FILTER_TYPE.NUMBER: { this.refs.numberFilter.cleanFiltered(); break; } case _Const2['default'].FILTER_TYPE.DATE: { this.refs.dateFilter.cleanFiltered(); break; } } } }, { key: 'applyFilter', value: function applyFilter(val) { if (this.props.filter === undefined) return; switch (this.props.filter.type) { case _Const2['default'].FILTER_TYPE.TEXT: { this.refs.textFilter.applyFilter(val); break; } case _Const2['default'].FILTER_TYPE.REGEX: { this.refs.regexFilter.applyFilter(val); break; } case _Const2['default'].FILTER_TYPE.SELECT: { this.refs.selectFilter.applyFilter(val); break; } case _Const2['default'].FILTER_TYPE.NUMBER: { this.refs.numberFilter.applyFilter(val); break; } case _Const2['default'].FILTER_TYPE.DATE: { this.refs.dateFilter.applyFilter(val); break; } } } }]); return TableHeaderColumn; })(_react.Component); var filterTypeArray = []; for (var key in _Const2['default'].FILTER_TYPE) { filterTypeArray.push(_Const2['default'].FILTER_TYPE[key]); } TableHeaderColumn.propTypes = { dataField: _react.PropTypes.string, dataAlign: _react.PropTypes.string, headerAlign: _react.PropTypes.string, dataSort: _react.PropTypes.bool, onSort: _react.PropTypes.func, dataFormat: _react.PropTypes.func, csvFormat: _react.PropTypes.func, csvHeader: _react.PropTypes.string, isKey: _react.PropTypes.bool, editable: _react.PropTypes.any, hidden: _react.PropTypes.bool, hiddenOnInsert: _react.PropTypes.bool, searchable: _react.PropTypes.bool, className: _react.PropTypes.string, width: _react.PropTypes.string, sortFunc: _react.PropTypes.func, sortFuncExtraData: _react.PropTypes.any, columnClassName: _react.PropTypes.any, columnTitle: _react.PropTypes.bool, filterFormatted: _react.PropTypes.bool, filterValue: _react.PropTypes.func, sort: _react.PropTypes.string, caretRender: _react.PropTypes.func, formatExtraData: _react.PropTypes.any, filter: _react.PropTypes.shape({ type: _react.PropTypes.oneOf(filterTypeArray), delay: _react.PropTypes.number, options: _react.PropTypes.oneOfType([_react.PropTypes.object, // for SelectFilter _react.PropTypes.arrayOf(_react.PropTypes.number) // for NumberFilter ]), numberComparators: _react.PropTypes.arrayOf(_react.PropTypes.string), emitter: _react.PropTypes.object, placeholder: _react.PropTypes.string, getElement: _react.PropTypes.func, customFilterParameters: _react.PropTypes.object }), sortIndicator: _react.PropTypes.bool, 'export': _react.PropTypes.bool }; TableHeaderColumn.defaultProps = { dataAlign: 'left', headerAlign: undefined, dataSort: false, dataFormat: undefined, csvFormat: undefined, csvHeader: undefined, isKey: false, editable: true, onSort: undefined, hidden: false, hiddenOnInsert: false, searchable: true, className: '', columnTitle: false, width: null, sortFunc: undefined, columnClassName: '', filterFormatted: false, filterValue: undefined, sort: undefined, formatExtraData: undefined, sortFuncExtraData: undefined, filter: undefined, sortIndicator: true }; exports['default'] = TableHeaderColumn; module.exports = exports['default']; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { /* eslint quotes: 0 */ /* eslint max-len: 0 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var legalComparators = ['=', '>', '>=', '<', '<=', '!=']; function dateParser(d) { return d.getFullYear() + '-' + ("0" + (d.getMonth() + 1)).slice(-2) + '-' + ("0" + d.getDate()).slice(-2); } var DateFilter = (function (_Component) { _inherits(DateFilter, _Component); function DateFilter(props) { _classCallCheck(this, DateFilter); _get(Object.getPrototypeOf(DateFilter.prototype), 'constructor', this).call(this, props); this.dateComparators = this.props.dateComparators || legalComparators; this.filter = this.filter.bind(this); this.onChangeComparator = this.onChangeComparator.bind(this); } _createClass(DateFilter, [{ key: 'setDefaultDate', value: function setDefaultDate() { var defaultDate = ''; var defaultValue = this.props.defaultValue; if (defaultValue && defaultValue.date) { // Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD" defaultDate = dateParser(new Date(defaultValue.date)); } return defaultDate; } }, { key: 'onChangeComparator', value: function onChangeComparator(event) { var date = this.refs.inputDate.value; var comparator = event.target.value; if (date === '') { return; } date = new Date(date); this.props.filterHandler({ date: date, comparator: comparator }, _Const2['default'].FILTER_TYPE.DATE); } }, { key: 'getComparatorOptions', value: function getComparatorOptions() { var optionTags = []; optionTags.push(_react2['default'].createElement('option', { key: '-1' })); for (var i = 0; i < this.dateComparators.length; i++) { optionTags.push(_react2['default'].createElement( 'option', { key: i, value: this.dateComparators[i] }, this.dateComparators[i] )); } return optionTags; } }, { key: 'filter', value: function filter(event) { var comparator = this.refs.dateFilterComparator.value; var dateValue = event.target.value; if (dateValue) { this.props.filterHandler({ date: new Date(dateValue), comparator: comparator }, _Const2['default'].FILTER_TYPE.DATE); } else { this.props.filterHandler(null, _Const2['default'].FILTER_TYPE.DATE); } } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.setDefaultDate(); var comparator = this.props.defaultValue ? this.props.defaultValue.comparator : ''; this.setState({ isPlaceholderSelected: value === '' }); this.refs.dateFilterComparator.value = comparator; this.refs.inputDate.value = value; this.props.filterHandler({ date: new Date(value), comparator: comparator }, _Const2['default'].FILTER_TYPE.DATE); } }, { key: 'applyFilter', value: function applyFilter(filterDateObj) { var date = filterDateObj.date; var comparator = filterDateObj.comparator; this.setState({ isPlaceholderSelected: date === '' }); this.refs.dateFilterComparator.value = comparator; this.refs.inputDate.value = dateParser(date); this.props.filterHandler({ date: date, comparator: comparator }, _Const2['default'].FILTER_TYPE.DATE); } }, { key: 'componentDidMount', value: function componentDidMount() { var comparator = this.refs.dateFilterComparator.value; var dateValue = this.refs.inputDate.value; if (comparator && dateValue) { this.props.filterHandler({ date: new Date(dateValue), comparator: comparator }, _Const2['default'].FILTER_TYPE.DATE); } } }, { key: 'render', value: function render() { var defaultValue = this.props.defaultValue; return _react2['default'].createElement( 'div', { className: 'filter date-filter' }, _react2['default'].createElement( 'select', { ref: 'dateFilterComparator', className: 'date-filter-comparator form-control', onChange: this.onChangeComparator, defaultValue: defaultValue ? defaultValue.comparator : '' }, this.getComparatorOptions() ), _react2['default'].createElement('input', { ref: 'inputDate', className: 'filter date-filter-input form-control', type: 'date', onChange: this.filter, defaultValue: this.setDefaultDate() }) ); } }]); return DateFilter; })(_react.Component); DateFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.shape({ date: _react.PropTypes.object, comparator: _react.PropTypes.oneOf(legalComparators) }), /* eslint consistent-return: 0 */ dateComparators: function dateComparators(props, propName) { if (!props[propName]) { return; } for (var i = 0; i < props[propName].length; i++) { var comparatorIsValid = false; for (var j = 0; j < legalComparators.length; j++) { if (legalComparators[j] === props[propName][i]) { comparatorIsValid = true; break; } } if (!comparatorIsValid) { return new Error('Date comparator provided is not supported.\n Use only ' + legalComparators); } } }, columnName: _react.PropTypes.string }; exports['default'] = DateFilter; module.exports = exports['default']; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var TextFilter = (function (_Component) { _inherits(TextFilter, _Component); function TextFilter(props) { _classCallCheck(this, TextFilter); _get(Object.getPrototypeOf(TextFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.timeout = null; } _createClass(TextFilter, [{ key: 'filter', value: function filter(event) { var _this = this; if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.TEXT); }, this.props.delay); } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.props.defaultValue ? this.props.defaultValue : ''; this.refs.inputText.value = value; this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.TEXT); } }, { key: 'applyFilter', value: function applyFilter(filterText) { this.refs.inputText.value = filterText; this.props.filterHandler(filterText, _Const2['default'].FILTER_TYPE.TEXT); } }, { key: 'componentDidMount', value: function componentDidMount() { var defaultValue = this.refs.inputText.value; if (defaultValue) { this.props.filterHandler(defaultValue, _Const2['default'].FILTER_TYPE.TEXT); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var _props = this.props; var placeholder = _props.placeholder; var columnName = _props.columnName; var defaultValue = _props.defaultValue; return _react2['default'].createElement('input', { ref: 'inputText', className: 'filter text-filter form-control', type: 'text', onChange: this.filter, placeholder: placeholder || 'Enter ' + columnName + '...', defaultValue: defaultValue ? defaultValue : '' }); } }]); return TextFilter; })(_react.Component); TextFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.string, delay: _react.PropTypes.number, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; TextFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = TextFilter; module.exports = exports['default']; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var RegexFilter = (function (_Component) { _inherits(RegexFilter, _Component); function RegexFilter(props) { _classCallCheck(this, RegexFilter); _get(Object.getPrototypeOf(RegexFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.timeout = null; } _createClass(RegexFilter, [{ key: 'filter', value: function filter(event) { var _this = this; if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.REGEX); }, this.props.delay); } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.props.defaultValue ? this.props.defaultValue : ''; this.refs.inputText.value = value; this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.TEXT); } }, { key: 'applyFilter', value: function applyFilter(filterRegx) { this.refs.inputText.value = filterRegx; this.props.filterHandler(filterRegx, _Const2['default'].FILTER_TYPE.REGEX); } }, { key: 'componentDidMount', value: function componentDidMount() { var value = this.refs.inputText.value; if (value) { this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.REGEX); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var _props = this.props; var defaultValue = _props.defaultValue; var placeholder = _props.placeholder; var columnName = _props.columnName; return _react2['default'].createElement('input', { ref: 'inputText', className: 'filter text-filter form-control', type: 'text', onChange: this.filter, placeholder: placeholder || 'Enter Regex for ' + columnName + '...', defaultValue: defaultValue ? defaultValue : '' }); } }]); return RegexFilter; })(_react.Component); RegexFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, defaultValue: _react.PropTypes.string, delay: _react.PropTypes.number, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; RegexFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = RegexFilter; module.exports = exports['default']; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var SelectFilter = (function (_Component) { _inherits(SelectFilter, _Component); function SelectFilter(props) { _classCallCheck(this, SelectFilter); _get(Object.getPrototypeOf(SelectFilter.prototype), 'constructor', this).call(this, props); this.filter = this.filter.bind(this); this.state = { isPlaceholderSelected: this.props.defaultValue === undefined || !this.props.options.hasOwnProperty(this.props.defaultValue) }; } _createClass(SelectFilter, [{ key: 'filter', value: function filter(event) { var value = event.target.value; this.setState({ isPlaceholderSelected: value === '' }); this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT); } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.props.defaultValue !== undefined ? this.props.defaultValue : ''; this.setState({ isPlaceholderSelected: value === '' }); this.refs.selectInput.value = value; this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT); } }, { key: 'applyFilter', value: function applyFilter(filterOption) { filterOption = filterOption + ''; this.setState({ isPlaceholderSelected: filterOption === '' }); this.refs.selectInput.value = filterOption; this.props.filterHandler(filterOption, _Const2['default'].FILTER_TYPE.SELECT); } }, { key: 'getOptions', value: function getOptions() { var optionTags = []; var _props = this.props; var options = _props.options; var placeholder = _props.placeholder; var columnName = _props.columnName; optionTags.push(_react2['default'].createElement( 'option', { key: '-1', value: '' }, placeholder || 'Select ' + columnName + '...' )); Object.keys(options).map(function (key) { optionTags.push(_react2['default'].createElement( 'option', { key: key, value: key }, options[key] + '' )); }); return optionTags; } }, { key: 'componentDidMount', value: function componentDidMount() { var value = this.refs.selectInput.value; if (value) { this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT); } } }, { key: 'render', value: function render() { var selectClass = (0, _classnames2['default'])('filter', 'select-filter', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected }); return _react2['default'].createElement( 'select', { ref: 'selectInput', className: selectClass, onChange: this.filter, defaultValue: this.props.defaultValue !== undefined ? this.props.defaultValue : '' }, this.getOptions() ); } }]); return SelectFilter; })(_react.Component); SelectFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, options: _react.PropTypes.object.isRequired, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; exports['default'] = SelectFilter; module.exports = exports['default']; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(3); var _classnames2 = _interopRequireDefault(_classnames); var _Const = __webpack_require__(4); var _Const2 = _interopRequireDefault(_Const); var legalComparators = ['=', '>', '>=', '<', '<=', '!=']; var NumberFilter = (function (_Component) { _inherits(NumberFilter, _Component); function NumberFilter(props) { _classCallCheck(this, NumberFilter); _get(Object.getPrototypeOf(NumberFilter.prototype), 'constructor', this).call(this, props); this.numberComparators = this.props.numberComparators || legalComparators; this.timeout = null; this.state = { isPlaceholderSelected: this.props.defaultValue === undefined || this.props.defaultValue.number === undefined || this.props.options && this.props.options.indexOf(this.props.defaultValue.number) === -1 }; this.onChangeNumber = this.onChangeNumber.bind(this); this.onChangeNumberSet = this.onChangeNumberSet.bind(this); this.onChangeComparator = this.onChangeComparator.bind(this); } _createClass(NumberFilter, [{ key: 'onChangeNumber', value: function onChangeNumber(event) { var _this = this; var comparator = this.refs.numberFilterComparator.value; if (comparator === '') { return; } if (this.timeout) { clearTimeout(this.timeout); } var filterValue = event.target.value; this.timeout = setTimeout(function () { _this.props.filterHandler({ number: filterValue, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); }, this.props.delay); } }, { key: 'onChangeNumberSet', value: function onChangeNumberSet(event) { var comparator = this.refs.numberFilterComparator.value; var value = event.target.value; this.setState({ isPlaceholderSelected: value === '' }); if (comparator === '') { return; } this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } }, { key: 'onChangeComparator', value: function onChangeComparator(event) { var value = this.refs.numberFilter.value; var comparator = event.target.value; if (value === '') { return; } this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } }, { key: 'cleanFiltered', value: function cleanFiltered() { var value = this.props.defaultValue ? this.props.defaultValue.number : ''; var comparator = this.props.defaultValue ? this.props.defaultValue.comparator : ''; this.setState({ isPlaceholderSelected: value === '' }); this.refs.numberFilterComparator.value = comparator; this.refs.numberFilter.value = value; this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } }, { key: 'applyFilter', value: function applyFilter(filterObj) { var number = filterObj.number; var comparator = filterObj.comparator; this.setState({ isPlaceholderSelected: number === '' }); this.refs.numberFilterComparator.value = comparator; this.refs.numberFilter.value = number; this.props.filterHandler({ number: number, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } }, { key: 'getComparatorOptions', value: function getComparatorOptions() { var optionTags = []; optionTags.push(_react2['default'].createElement('option', { key: '-1' })); for (var i = 0; i < this.numberComparators.length; i++) { optionTags.push(_react2['default'].createElement( 'option', { key: i, value: this.numberComparators[i] }, this.numberComparators[i] )); } return optionTags; } }, { key: 'getNumberOptions', value: function getNumberOptions() { var optionTags = []; var options = this.props.options; optionTags.push(_react2['default'].createElement( 'option', { key: '-1', value: '' }, this.props.placeholder || 'Select ' + this.props.columnName + '...' )); for (var i = 0; i < options.length; i++) { optionTags.push(_react2['default'].createElement( 'option', { key: i, value: options[i] }, options[i] )); } return optionTags; } }, { key: 'componentDidMount', value: function componentDidMount() { var comparator = this.refs.numberFilterComparator.value; var number = this.refs.numberFilter.value; if (comparator && number) { this.props.filterHandler({ number: number, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { clearTimeout(this.timeout); } }, { key: 'render', value: function render() { var selectClass = (0, _classnames2['default'])('select-filter', 'number-filter-input', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected }); return _react2['default'].createElement( 'div', { className: 'filter number-filter' }, _react2['default'].createElement( 'select', { ref: 'numberFilterComparator', className: 'number-filter-comparator form-control', onChange: this.onChangeComparator, defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : '' }, this.getComparatorOptions() ), this.props.options ? _react2['default'].createElement( 'select', { ref: 'numberFilter', className: selectClass, onChange: this.onChangeNumberSet, defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' }, this.getNumberOptions() ) : _react2['default'].createElement('input', { ref: 'numberFilter', type: 'number', className: 'number-filter-input form-control', placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...', onChange: this.onChangeNumber, defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' }) ); } }]); return NumberFilter; })(_react.Component); NumberFilter.propTypes = { filterHandler: _react.PropTypes.func.isRequired, options: _react.PropTypes.arrayOf(_react.PropTypes.number), defaultValue: _react.PropTypes.shape({ number: _react.PropTypes.number, comparator: _react.PropTypes.oneOf(legalComparators) }), delay: _react.PropTypes.number, /* eslint consistent-return: 0 */ numberComparators: function numberComparators(props, propName) { if (!props[propName]) { return; } for (var i = 0; i < props[propName].length; i++) { var comparatorIsValid = false; for (var j = 0; j < legalComparators.length; j++) { if (legalComparators[j] === props[propName][i]) { comparatorIsValid = true; break; } } if (!comparatorIsValid) { return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators); } } }, placeholder: _react.PropTypes.string, columnName: _react.PropTypes.string }; NumberFilter.defaultProps = { delay: _Const2['default'].FILTER_DELAY }; exports['default'] = NumberFilter; module.exports = exports['default']; /***/ } /******/ ]) }); ; //# sourceMappingURL=react-bootstrap-table.js.map
ajax/libs/webshim/1.15.1-RC1/dev/shims/es6.js
ahocevar/cdnjs
// ES6-shim 0.15.0 (c) 2013-2014 Paul Miller (http://paulmillr.com) // ES6-shim may be freely distributed under the MIT license. // For more details and documentation: // https://github.com/paulmillr/es6-shim/ webshim.register('es6', function($, webshim, window, document, undefined){ 'use strict'; var isCallableWithoutNew = function(func) { try { func(); } catch (e) { return false; } return true; }; var supportsSubclassing = function(C, f) { /* jshint proto:true */ try { var Sub = function() { C.apply(this, arguments); }; if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ } Object.setPrototypeOf(Sub, C); Sub.prototype = Object.create(C.prototype, { constructor: { value: C } }); return f(Sub); } catch (e) { return false; } }; var arePropertyDescriptorsSupported = function() { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { /* this is IE 8. */ return false; } }; var startsWithRejectsRegex = function() { var rejectsRegex = false; if (String.prototype.startsWith) { try { '/a/'.startsWith(/a/); } catch (e) { /* this is spec compliant */ rejectsRegex = true; } } return rejectsRegex; }; /*jshint evil: true */ var getGlobal = new Function('return this;'); /*jshint evil: false */ var main = function() { var globals = getGlobal(); var global_isFinite = globals.isFinite; var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported(); var startsWithIsCompliant = startsWithRejectsRegex(); var _slice = Array.prototype.slice; var _indexOf = String.prototype.indexOf; var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var ArrayIterator; // make our implementation private // Define configurable, writable and non-enumerable props // if they don’t exist. var defineProperties = function(object, map) { Object.keys(map).forEach(function(name) { var method = map[name]; if (name in object) return; if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: method }); } else { object[name] = method; } }); }; // Simple shim for Object.create on ES3 browsers // (unlike real shim, no attempt to support `prototype === null`) var create = Object.create || function(prototype, properties) { function Type() {} Type.prototype = prototype; var object = new Type(); if (typeof properties !== "undefined") { defineProperties(object, properties); } return object; }; // This is a private name in the es6 spec, equal to '[Symbol.iterator]' // we're going to use an arbitrary _-prefixed name to make our shims // work properly with each other, even though we don't have full Iterator // support. That is, `Array.from(map.keys())` will work, but we don't // pretend to export a "real" Iterator interface. var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var addIterator = function(prototype, impl) { if (!impl) { impl = function iterator() { return this; }; } var o = {}; o[$iterator$] = impl; defineProperties(prototype, o); }; // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js // can be replaced with require('is-arguments') if we ever use a build process instead var isArguments = function isArguments(value) { var str = _toString.call(value); var result = str === '[object Arguments]'; if (!result) { result = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && _toString.call(value.callee) === '[object Function]'; } return result; }; var emulateES6construct = function(o) { if (!ES.TypeIsObject(o)) throw new TypeError('bad object'); // es5 approximation to es6 subclass semantics: in es6, 'new Foo' // would invoke Foo.@@create to allocation/initialize the new object. // In es5 we just get the plain object. So if we detect an // uninitialized object, invoke o.constructor.@@create if (!o._es6construct) { if (o.constructor && ES.IsCallable(o.constructor['@@create'])) { o = o.constructor['@@create'](o); } defineProperties(o, { _es6construct: true }); } return o; }; var ES = { CheckObjectCoercible: function(x, optMessage) { /* jshint eqnull:true */ if (x == null) throw new TypeError(optMessage || ('Cannot call method on ' + x)); return x; }, TypeIsObject: function(x) { /* jshint eqnull:true */ // this is expensive when it returns false; use this function // when you expect it to return true in the common case. return x != null && Object(x) === x; }, ToObject: function(o, optMessage) { return Object(ES.CheckObjectCoercible(o, optMessage)); }, IsCallable: function(x) { return typeof x === 'function' && // some versions of IE say that typeof /abc/ === 'function' _toString.call(x) === '[object Function]'; }, ToInt32: function(x) { return x >> 0; }, ToUint32: function(x) { return x >>> 0; }, ToInteger: function(value) { var number = +value; if (Number.isNaN(number)) return 0; if (number === 0 || !Number.isFinite(number)) return number; return Math.sign(number) * Math.floor(Math.abs(number)); }, ToLength: function(value) { var len = ES.ToInteger(value); if (len <= 0) return 0; // includes converting -0 to +0 if (len > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER; return len; }, SameValue: function(a, b) { if (a === b) { // 0 === -0, but they are not identical. if (a === 0) return 1 / a === 1 / b; return true; } return Number.isNaN(a) && Number.isNaN(b); }, SameValueZero: function(a, b) { // same as SameValue except for SameValueZero(+0, -0) == true return (a === b) || (Number.isNaN(a) && Number.isNaN(b)); }, IsIterable: function(o) { return ES.TypeIsObject(o) && (o[$iterator$] !== undefined || isArguments(o)); }, GetIterator: function(o) { if (isArguments(o)) { // special case support for `arguments` return new ArrayIterator(o, "value"); } var it = o[$iterator$](); if (!ES.TypeIsObject(it)) { throw new TypeError('bad iterator'); } return it; }, IteratorNext: function(it) { var result = (arguments.length > 1) ? it.next(arguments[1]) : it.next(); if (!ES.TypeIsObject(result)) { throw new TypeError('bad iterator'); } return result; }, Construct: function(C, args) { // CreateFromConstructor var obj; if (ES.IsCallable(C['@@create'])) { obj = C['@@create'](); } else { // OrdinaryCreateFromConstructor obj = create(C.prototype || null); } // Mark that we've used the es6 construct path // (see emulateES6construct) defineProperties(obj, { _es6construct: true }); // Call the constructor. var result = C.apply(obj, args); return ES.TypeIsObject(result) ? result : obj; } }; var numberConversion = (function () { // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266 // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200 function roundToEven(n) { var w = Math.floor(n), f = n - w; if (f < 0.5) { return w; } if (f > 0.5) { return w + 1; } return w % 2 ? w + 1 : w; } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str, bytes; // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = Math.pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023); f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits)); if (f / Math.pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normal e = e + bias; f = f - Math.pow(2, fbits); } } else { // Subnormal e = 0; f = roundToEven(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.slice(0, 8), 2)); str = str.slice(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.slice(0, 1), 2) ? -1 : 1; e = parseInt(str.slice(1, 1 + ebits), 2); f = parseInt(str.slice(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); } function packFloat64(v) { return packIEEE754(v, 11, 52); } function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); } function packFloat32(v) { return packIEEE754(v, 8, 23); } var conversions = { toFloat32: function (num) { return unpackFloat32(packFloat32(num)); } }; if (typeof Float32Array !== 'undefined') { var float32array = new Float32Array(1); conversions.toFloat32 = function (num) { float32array[0] = num; return float32array[0]; }; } return conversions; }()); defineProperties(String, { fromCodePoint: function(_) { // length = 1 var points = _slice.call(arguments, 0, arguments.length); var result = []; var next; for (var i = 0, length = points.length; i < length; i++) { next = Number(points[i]); if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) { throw new RangeError('Invalid code point ' + next); } if (next < 0x10000) { result.push(String.fromCharCode(next)); } else { next -= 0x10000; result.push(String.fromCharCode((next >> 10) + 0xD800)); result.push(String.fromCharCode((next % 0x400) + 0xDC00)); } } return result.join(''); }, raw: function(callSite) { // raw.length===1 var substitutions = _slice.call(arguments, 1, arguments.length); var cooked = ES.ToObject(callSite, 'bad callSite'); var rawValue = cooked.raw; var raw = ES.ToObject(rawValue, 'bad raw value'); var len = Object.keys(raw).length; var literalsegments = ES.ToLength(len); if (literalsegments === 0) { return ''; } var stringElements = []; var nextIndex = 0; var nextKey, next, nextSeg, nextSub; while (nextIndex < literalsegments) { nextKey = String(nextIndex); next = raw[nextKey]; nextSeg = String(next); stringElements.push(nextSeg); if (nextIndex + 1 >= literalsegments) { break; } next = substitutions[nextKey]; if (next === undefined) { break; } nextSub = String(next); stringElements.push(nextSub); nextIndex++; } return stringElements.join(''); } }); var StringShims = { // Fast repeat, uses the `Exponentiation by squaring` algorithm. // Perf: http://jsperf.com/string-repeat2/2 repeat: (function() { var repeat = function(s, times) { if (times < 1) return ''; if (times % 2) return repeat(s, times - 1) + s; var half = repeat(s, times / 2); return half + half; }; return function(times) { var thisStr = String(ES.CheckObjectCoercible(this)); times = ES.ToInteger(times); if (times < 0 || times === Infinity) { throw new RangeError('Invalid String#repeat value'); } return repeat(thisStr, times); }; })(), startsWith: function(searchStr) { var thisStr = String(ES.CheckObjectCoercible(this)); if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "startsWith" with a regex'); searchStr = String(searchStr); var startArg = arguments.length > 1 ? arguments[1] : undefined; var start = Math.max(ES.ToInteger(startArg), 0); return thisStr.slice(start, start + searchStr.length) === searchStr; }, endsWith: function(searchStr) { var thisStr = String(ES.CheckObjectCoercible(this)); if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "endsWith" with a regex'); searchStr = String(searchStr); var thisLen = thisStr.length; var posArg = arguments.length > 1 ? arguments[1] : undefined; var pos = posArg === undefined ? thisLen : ES.ToInteger(posArg); var end = Math.min(Math.max(pos, 0), thisLen); return thisStr.slice(end - searchStr.length, end) === searchStr; }, contains: function(searchString) { var position = arguments.length > 1 ? arguments[1] : undefined; // Somehow this trick makes method 100% compat with the spec. return _indexOf.call(this, searchString, position) !== -1; }, codePointAt: function(pos) { var thisStr = String(ES.CheckObjectCoercible(this)); var position = ES.ToInteger(pos); var length = thisStr.length; if (position < 0 || position >= length) return undefined; var first = thisStr.charCodeAt(position); var isEnd = (position + 1 === length); if (first < 0xD800 || first > 0xDBFF || isEnd) return first; var second = thisStr.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) return first; return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000; } }; defineProperties(String.prototype, StringShims); var hasStringTrimBug = '\u0085'.trim().length !== 1; if (hasStringTrimBug) { var originalStringTrim = String.prototype.trim; delete String.prototype.trim; // whitespace from: http://es5.github.io/#x15.5.4.20 // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 var ws = [ '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF' ].join(''); var trimBeginRegexp = new RegExp('^[' + ws + '][' + ws + ']*'); var trimEndRegexp = new RegExp('[' + ws + '][' + ws + ']*$'); defineProperties(String.prototype, { trim: function() { if (this === undefined || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); } }); } // see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator var StringIterator = function(s) { this._s = String(ES.CheckObjectCoercible(s)); this._i = 0; }; StringIterator.prototype.next = function() { var s = this._s, i = this._i; if (s === undefined || i >= s.length) { this._s = undefined; return { value: undefined, done: true }; } var first = s.charCodeAt(i), second, len; if (first < 0xD800 || first > 0xDBFF || (i+1) == s.length) { len = 1; } else { second = s.charCodeAt(i+1); len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2; } this._i = i + len; return { value: s.substr(i, len), done: false }; }; addIterator(StringIterator.prototype); addIterator(String.prototype, function() { return new StringIterator(this); }); if (!startsWithIsCompliant) { // Firefox has a noncompliant startsWith implementation String.prototype.startsWith = StringShims.startsWith; String.prototype.endsWith = StringShims.endsWith; } defineProperties(Array, { from: function(iterable) { var mapFn = arguments.length > 1 ? arguments[1] : undefined; var thisArg = arguments.length > 2 ? arguments[2] : undefined; var list = ES.ToObject(iterable, 'bad iterable'); if (mapFn !== undefined && !ES.IsCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } var usingIterator = ES.IsIterable(list); // does the spec really mean that Arrays should use ArrayIterator? // https://bugs.ecmascript.org/show_bug.cgi?id=2416 //if (Array.isArray(list)) { usingIterator=false; } var length = usingIterator ? 0 : ES.ToLength(list.length); var result = ES.IsCallable(this) ? Object(usingIterator ? new this() : new this(length)) : new Array(length); var it = usingIterator ? ES.GetIterator(list) : null; var value; for (var i = 0; usingIterator || (i < length); i++) { if (usingIterator) { value = ES.IteratorNext(it); if (value.done) { length = i; break; } value = value.value; } else { value = list[i]; } if (mapFn) { result[i] = thisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } } result.length = length; return result; }, of: function() { return Array.from(arguments); } }); // Our ArrayIterator is private; see // https://github.com/paulmillr/es6-shim/issues/252 ArrayIterator = function(array, kind) { this.i = 0; this.array = array; this.kind = kind; }; defineProperties(ArrayIterator.prototype, { next: function() { var i = this.i, array = this.array; if (i === undefined || this.kind === undefined) { throw new TypeError('Not an ArrayIterator'); } if (array!==undefined) { var len = ES.ToLength(array.length); for (; i < len; i++) { var kind = this.kind; var retval; if (kind === "key") { retval = i; } else if (kind === "value") { retval = array[i]; } else if (kind === "entry") { retval = [i, array[i]]; } this.i = i + 1; return { value: retval, done: false }; } } this.array = undefined; return { value: undefined, done: true }; } }); addIterator(ArrayIterator.prototype); defineProperties(Array.prototype, { copyWithin: function(target, start) { var end = arguments[2]; // copyWithin.length must be 2 var o = ES.ToObject(this); var len = ES.ToLength(o.length); target = ES.ToInteger(target); start = ES.ToInteger(start); var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); end = (end===undefined) ? len : ES.ToInteger(end); var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); var count = Math.min(fin - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (_hasOwnProperty.call(o, from)) { o[to] = o[from]; } else { delete o[from]; } from += direction; to += direction; count -= 1; } return o; }, fill: function(value) { var start = arguments.length > 1 ? arguments[1] : undefined; var end = arguments.length > 2 ? arguments[2] : undefined; var O = ES.ToObject(this); var len = ES.ToLength(O.length); start = ES.ToInteger(start === undefined ? 0 : start); end = ES.ToInteger(end === undefined ? len : end); var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); var relativeEnd = end < 0 ? len + end : end; for (var i = relativeStart; i < len && i < relativeEnd; ++i) { O[i] = value; } return O; }, find: function(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#find: predicate must be a function'); } var thisArg = arguments[1]; for (var i = 0, value; i < length; i++) { if (i in list) { value = list[i]; if (predicate.call(thisArg, value, i, list)) return value; } } return undefined; }, findIndex: function(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#findIndex: predicate must be a function'); } var thisArg = arguments[1]; for (var i = 0; i < length; i++) { if (i in list) { if (predicate.call(thisArg, list[i], i, list)) return i; } } return -1; }, keys: function() { return new ArrayIterator(this, "key"); }, values: function() { return new ArrayIterator(this, "value"); }, entries: function() { return new ArrayIterator(this, "entry"); } }); addIterator(Array.prototype, function() { return this.values(); }); // Chrome defines keys/values/entries on Array, but doesn't give us // any way to identify its iterator. So add our own shimmed field. if (Object.getPrototypeOf) { addIterator(Object.getPrototypeOf([].values())); } var maxSafeInteger = Math.pow(2, 53) - 1; defineProperties(Number, { MAX_SAFE_INTEGER: maxSafeInteger, MIN_SAFE_INTEGER: -maxSafeInteger, EPSILON: 2.220446049250313e-16, parseInt: globals.parseInt, parseFloat: globals.parseFloat, isFinite: function(value) { return typeof value === 'number' && global_isFinite(value); }, isInteger: function(value) { return Number.isFinite(value) && ES.ToInteger(value) === value; }, isSafeInteger: function(value) { return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; }, isNaN: function(value) { // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is NaN. // isNaN is broken: it converts its argument to number, so // isNaN('foo') => true return value !== value; } }); if (supportsDescriptors) { defineProperties(Object, { getPropertyDescriptor: function(subject, name) { var pd = Object.getOwnPropertyDescriptor(subject, name); var proto = Object.getPrototypeOf(subject); while (pd === undefined && proto !== null) { pd = Object.getOwnPropertyDescriptor(proto, name); proto = Object.getPrototypeOf(proto); } return pd; }, getPropertyNames: function(subject) { var result = Object.getOwnPropertyNames(subject); var proto = Object.getPrototypeOf(subject); var addProperty = function(property) { if (result.indexOf(property) === -1) { result.push(property); } }; while (proto !== null) { Object.getOwnPropertyNames(proto).forEach(addProperty); proto = Object.getPrototypeOf(proto); } return result; } }); defineProperties(Object, { // 19.1.3.1 assign: function(target, source) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } return Array.prototype.reduce.call(arguments, function(target, source) { return Object.keys(Object(source)).reduce(function(target, key) { target[key] = source[key]; return target; }, target); }); }, is: function(a, b) { return ES.SameValue(a, b); }, // 19.1.3.9 // shim from https://gist.github.com/WebReflection/5593554 setPrototypeOf: (function(Object, magic) { var set; var checkArgs = function(O, proto) { if (!ES.TypeIsObject(O)) { throw new TypeError('cannot set prototype on a non-object'); } if (!(proto===null || ES.TypeIsObject(proto))) { throw new TypeError('can only set prototype to an object or null'+proto); } }; var setPrototypeOf = function(O, proto) { checkArgs(O, proto); set.call(O, proto); return O; }; try { // this works already in Firefox and Safari set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set; set.call({}, null); } catch (e) { if (Object.prototype !== {}[magic]) { // IE < 11 cannot be shimmed return; } // probably Chrome or some old Mobile stock browser set = function(proto) { this[magic] = proto; }; // please note that this will **not** work // in those browsers that do not inherit // __proto__ by mistake from Object.prototype // in these cases we should probably throw an error // or at least be informed about the issue setPrototypeOf.polyfill = setPrototypeOf( setPrototypeOf({}, null), Object.prototype ) instanceof Object; // setPrototypeOf.polyfill === true means it works as meant // setPrototypeOf.polyfill === false means it's not 100% reliable // setPrototypeOf.polyfill === undefined // or // setPrototypeOf.polyfill == null means it's not a polyfill // which means it works as expected // we can even delete Object.prototype.__proto__; } return setPrototypeOf; })(Object, '__proto__') }); } // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work, // but Object.create(null) does. if (Object.setPrototypeOf && Object.getPrototypeOf && Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null && Object.getPrototypeOf(Object.create(null)) === null) { (function() { var FAKENULL = Object.create(null); var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf; Object.getPrototypeOf = function(o) { var result = gpo(o); return result === FAKENULL ? null : result; }; Object.setPrototypeOf = function(o, p) { if (p === null) { p = FAKENULL; } return spo(o, p); }; Object.setPrototypeOf.polyfill = false; })(); } try { Object.keys('foo'); } catch (e) { var originalObjectKeys = Object.keys; Object.keys = function (obj) { return originalObjectKeys(ES.ToObject(obj)); }; } var MathShims = { acosh: function(value) { value = Number(value); if (Number.isNaN(value) || value < 1) return NaN; if (value === 1) return 0; if (value === Infinity) return value; return Math.log(value + Math.sqrt(value * value - 1)); }, asinh: function(value) { value = Number(value); if (value === 0 || !global_isFinite(value)) { return value; } return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1)); }, atanh: function(value) { value = Number(value); if (Number.isNaN(value) || value < -1 || value > 1) { return NaN; } if (value === -1) return -Infinity; if (value === 1) return Infinity; if (value === 0) return value; return 0.5 * Math.log((1 + value) / (1 - value)); }, cbrt: function(value) { value = Number(value); if (value === 0) return value; var negate = value < 0, result; if (negate) value = -value; result = Math.pow(value, 1/3); return negate ? -result : result; }, clz32: function(value) { // See https://bugs.ecmascript.org/show_bug.cgi?id=2465 value = Number(value); var number = ES.ToUint32(value); if (number === 0) { return 32; } return 32 - (number).toString(2).length; }, cosh: function(value) { value = Number(value); if (value === 0) return 1; // +0 or -0 if (Number.isNaN(value)) return NaN; if (!global_isFinite(value)) return Infinity; if (value < 0) value = -value; if (value > 21) return Math.exp(value) / 2; return (Math.exp(value) + Math.exp(-value)) / 2; }, expm1: function(value) { value = Number(value); if (value === -Infinity) return -1; if (!global_isFinite(value) || value === 0) return value; return Math.exp(value) - 1; }, hypot: function(x, y) { var anyNaN = false; var allZero = true; var anyInfinity = false; var numbers = []; Array.prototype.every.call(arguments, function(arg) { var num = Number(arg); if (Number.isNaN(num)) anyNaN = true; else if (num === Infinity || num === -Infinity) anyInfinity = true; else if (num !== 0) allZero = false; if (anyInfinity) { return false; } else if (!anyNaN) { numbers.push(Math.abs(num)); } return true; }); if (anyInfinity) return Infinity; if (anyNaN) return NaN; if (allZero) return 0; numbers.sort(function (a, b) { return b - a; }); var largest = numbers[0]; var divided = numbers.map(function (number) { return number / largest; }); var sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0); return largest * Math.sqrt(sum); }, log2: function(value) { return Math.log(value) * Math.LOG2E; }, log10: function(value) { return Math.log(value) * Math.LOG10E; }, log1p: function(value) { value = Number(value); if (value < -1 || Number.isNaN(value)) return NaN; if (value === 0 || value === Infinity) return value; if (value === -1) return -Infinity; var result = 0; var n = 50; if (value < 0 || value > 1) return Math.log(1 + value); for (var i = 1; i < n; i++) { if ((i % 2) === 0) { result -= Math.pow(value, i) / i; } else { result += Math.pow(value, i) / i; } } return result; }, sign: function(value) { var number = +value; if (number === 0) return number; if (Number.isNaN(number)) return number; return number < 0 ? -1 : 1; }, sinh: function(value) { value = Number(value); if (!global_isFinite(value) || value === 0) return value; return (Math.exp(value) - Math.exp(-value)) / 2; }, tanh: function(value) { value = Number(value); if (Number.isNaN(value) || value === 0) return value; if (value === Infinity) return 1; if (value === -Infinity) return -1; return (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value)); }, trunc: function(value) { var number = Number(value); return number < 0 ? -Math.floor(-number) : Math.floor(number); }, imul: function(x, y) { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul x = ES.ToUint32(x); y = ES.ToUint32(y); var ah = (x >>> 16) & 0xffff; var al = x & 0xffff; var bh = (y >>> 16) & 0xffff; var bl = y & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0); }, fround: function(x) { if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) { return x; } var num = Number(x); return numberConversion.toFloat32(num); } }; defineProperties(Math, MathShims); if (Math.imul(0xffffffff, 5) !== -5) { // Safari 6.1, at least, reports "0" for this value Math.imul = MathShims.imul; } // Promises // Simplest possible implementation; use a 3rd-party library if you // want the best possible speed and/or long stack traces. var PromiseShim = (function() { var Promise, Promise$prototype; ES.IsPromise = function(promise) { if (!ES.TypeIsObject(promise)) { return false; } if (!promise._promiseConstructor) { // _promiseConstructor is a bit more unique than _status, so we'll // check that instead of the [[PromiseStatus]] internal field. return false; } if (promise._status === undefined) { return false; // uninitialized } return true; }; // "PromiseCapability" in the spec is what most promise implementations // call a "deferred". var PromiseCapability = function(C) { if (!ES.IsCallable(C)) { throw new TypeError('bad promise constructor'); } var capability = this; var resolver = function(resolve, reject) { capability.resolve = resolve; capability.reject = reject; }; capability.promise = ES.Construct(C, [resolver]); // see https://bugs.ecmascript.org/show_bug.cgi?id=2478 if (!capability.promise._es6construct) { throw new TypeError('bad promise constructor'); } if (!(ES.IsCallable(capability.resolve) && ES.IsCallable(capability.reject))) { throw new TypeError('bad promise constructor'); } }; // find an appropriate setImmediate-alike var setTimeout = globals.setTimeout; var makeZeroTimeout; if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) { makeZeroTimeout = function() { // from http://dbaron.org/log/20100309-faster-timeouts var timeouts = []; var messageName = "zero-timeout-message"; var setZeroTimeout = function(fn) { timeouts.push(fn); window.postMessage(messageName, "*"); }; var handleMessage = function(event) { if (event.source == window && event.data == messageName) { event.stopPropagation(); if (timeouts.length === 0) { return; } var fn = timeouts.shift(); fn(); } }; window.addEventListener("message", handleMessage, true); return setZeroTimeout; }; } var makePromiseAsap = function() { // An efficient task-scheduler based on a pre-existing Promise // implementation, which we can use even if we override the // global Promise below (in order to workaround bugs) // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671 var P = globals.Promise; return P && P.resolve && function(task) { return P.resolve().then(task); }; }; var enqueue = ES.IsCallable(globals.setImmediate) ? globals.setImmediate.bind(globals) : typeof process === 'object' && process.nextTick ? process.nextTick : makePromiseAsap() || (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() : function(task) { setTimeout(task, 0); }); // fallback var triggerPromiseReactions = function(reactions, x) { reactions.forEach(function(reaction) { enqueue(function() { // PromiseReactionTask var handler = reaction.handler; var capability = reaction.capability; var resolve = capability.resolve; var reject = capability.reject; try { var result = handler(x); if (result === capability.promise) { throw new TypeError('self resolution'); } var updateResult = updatePromiseFromPotentialThenable(result, capability); if (!updateResult) { resolve(result); } } catch (e) { reject(e); } }); }); }; var updatePromiseFromPotentialThenable = function(x, capability) { if (!ES.TypeIsObject(x)) { return false; } var resolve = capability.resolve; var reject = capability.reject; try { var then = x.then; // only one invocation of accessor if (!ES.IsCallable(then)) { return false; } then.call(x, resolve, reject); } catch(e) { reject(e); } return true; }; var promiseResolutionHandler = function(promise, onFulfilled, onRejected){ return function(x) { if (x === promise) { return onRejected(new TypeError('self resolution')); } var C = promise._promiseConstructor; var capability = new PromiseCapability(C); var updateResult = updatePromiseFromPotentialThenable(x, capability); if (updateResult) { return capability.promise.then(onFulfilled, onRejected); } else { return onFulfilled(x); } }; }; Promise = function(resolver) { var promise = this; promise = emulateES6construct(promise); if (!promise._promiseConstructor) { // we use _promiseConstructor as a stand-in for the internal // [[PromiseStatus]] field; it's a little more unique. throw new TypeError('bad promise'); } if (promise._status !== undefined) { throw new TypeError('promise already initialized'); } // see https://bugs.ecmascript.org/show_bug.cgi?id=2482 if (!ES.IsCallable(resolver)) { throw new TypeError('not a valid resolver'); } promise._status = 'unresolved'; promise._resolveReactions = []; promise._rejectReactions = []; var resolve = function(resolution) { if (promise._status !== 'unresolved') { return; } var reactions = promise._resolveReactions; promise._result = resolution; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-resolution'; triggerPromiseReactions(reactions, resolution); }; var reject = function(reason) { if (promise._status !== 'unresolved') { return; } var reactions = promise._rejectReactions; promise._result = reason; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-rejection'; triggerPromiseReactions(reactions, reason); }; try { resolver(resolve, reject); } catch (e) { reject(e); } return promise; }; Promise$prototype = Promise.prototype; defineProperties(Promise, { '@@create': function(obj) { var constructor = this; // AllocatePromise // The `obj` parameter is a hack we use for es5 // compatibility. var prototype = constructor.prototype || Promise$prototype; obj = obj || create(prototype); defineProperties(obj, { _status: undefined, _result: undefined, _resolveReactions: undefined, _rejectReactions: undefined, _promiseConstructor: undefined }); obj._promiseConstructor = constructor; return obj; } }); var _promiseAllResolver = function(index, values, capability, remaining) { var done = false; return function(x) { if (done) { return; } // protect against being called multiple times done = true; values[index] = x; if ((--remaining.count) === 0) { var resolve = capability.resolve; resolve(values); // call w/ this===undefined } }; }; Promise.all = function(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); var values = [], remaining = { count: 1 }; for (var index = 0; ; index++) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextPromise = C.resolve(next.value); var resolveElement = _promiseAllResolver( index, values, capability, remaining ); remaining.count++; nextPromise.then(resolveElement, capability.reject); } if ((--remaining.count) === 0) { resolve(values); // call w/ this===undefined } } catch (e) { reject(e); } return capability.promise; }; Promise.race = function(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); while (true) { var next = ES.IteratorNext(it); if (next.done) { // If iterable has no items, resulting promise will never // resolve; see: // https://github.com/domenic/promises-unwrapping/issues/75 // https://bugs.ecmascript.org/show_bug.cgi?id=2515 break; } var nextPromise = C.resolve(next.value); nextPromise.then(resolve, reject); } } catch (e) { reject(e); } return capability.promise; }; Promise.reject = function(reason) { var C = this; var capability = new PromiseCapability(C); var reject = capability.reject; reject(reason); // call with this===undefined return capability.promise; }; Promise.resolve = function(v) { var C = this; if (ES.IsPromise(v)) { var constructor = v._promiseConstructor; if (constructor === C) { return v; } } var capability = new PromiseCapability(C); var resolve = capability.resolve; resolve(v); // call with this===undefined return capability.promise; }; Promise.prototype['catch'] = function( onRejected ) { return this.then(undefined, onRejected); }; Promise.prototype.then = function( onFulfilled, onRejected ) { var promise = this; if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); } // this.constructor not this._promiseConstructor; see // https://bugs.ecmascript.org/show_bug.cgi?id=2513 var C = this.constructor; var capability = new PromiseCapability(C); if (!ES.IsCallable(onRejected)) { onRejected = function(e) { throw e; }; } if (!ES.IsCallable(onFulfilled)) { onFulfilled = function(x) { return x; }; } var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected); var resolveReaction = { capability: capability, handler: resolutionHandler }; var rejectReaction = { capability: capability, handler: onRejected }; switch (promise._status) { case 'unresolved': promise._resolveReactions.push(resolveReaction); promise._rejectReactions.push(rejectReaction); break; case 'has-resolution': triggerPromiseReactions([resolveReaction], promise._result); break; case 'has-rejection': triggerPromiseReactions([rejectReaction], promise._result); break; default: throw new TypeError('unexpected'); } return capability.promise; }; return Promise; })(); // export the Promise constructor. defineProperties(globals, { Promise: PromiseShim }); // In Chrome 33 (and thereabouts) Promise is defined, but the // implementation is buggy in a number of ways. Let's check subclassing // support to see if we have a buggy implementation. var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function(S) { return S.resolve(42) instanceof S; }); var promiseIgnoresNonFunctionThenCallbacks = (function () { try { globals.Promise.reject(42).then(null, 5).then(null, function () {}); return true; } catch (ex) { return false; } }()); if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks) { globals.Promise = PromiseShim; } // Map and Set require a true ES5 environment if (supportsDescriptors) { var fastkey = function fastkey(key) { var type = typeof key; if (type === 'string') { return '$' + key; } else if (type === 'number') { // note that -0 will get coerced to "0" when used as a property key return key; } return null; }; var emptyObject = function emptyObject() { // accomodate some older not-quite-ES5 browsers return Object.create ? Object.create(null) : {}; }; var collectionShims = { Map: (function() { var empty = {}; function MapEntry(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; } MapEntry.prototype.isRemoved = function() { return this.key === empty; }; function MapIterator(map, kind) { this.head = map._head; this.i = this.head; this.kind = kind; } MapIterator.prototype = { next: function() { var i = this.i, kind = this.kind, head = this.head, result; if (this.i === undefined) { return { value: undefined, done: true }; } while (i.isRemoved() && i !== head) { // back up off of removed entries i = i.prev; } // advance to next unreturned element. while (i.next !== head) { i = i.next; if (!i.isRemoved()) { if (kind === "key") { result = i.key; } else if (kind === "value") { result = i.value; } else { result = [i.key, i.value]; } this.i = i; return { value: result, done: false }; } } // once the iterator is done, it is done forever. this.i = undefined; return { value: undefined, done: true }; } }; addIterator(MapIterator.prototype); function Map(iterable) { var map = this; map = emulateES6construct(map); if (!map._es6map) { throw new TypeError('bad map'); } var head = new MapEntry(null, null); // circular doubly-linked list. head.next = head.prev = head; defineProperties(map, { '_head': head, '_storage': emptyObject(), '_size': 0 }); // Optionally initialize map from iterable if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = map.set; if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; if (!ES.TypeIsObject(nextItem)) { throw new TypeError('expected iterable of pairs'); } adder.call(map, nextItem[0], nextItem[1]); } } return map; } var Map$prototype = Map.prototype; defineProperties(Map, { '@@create': function(obj) { var constructor = this; var prototype = constructor.prototype || Map$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6map: true }); return obj; } }); Object.defineProperty(Map.prototype, 'size', { configurable: true, enumerable: false, get: function() { if (typeof this._size === 'undefined') { throw new TypeError('size method called on incompatible Map'); } return this._size; } }); defineProperties(Map.prototype, { get: function(key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path var entry = this._storage[fkey]; return entry ? entry.value : undefined; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return i.value; } } return undefined; }, has: function(key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path return typeof this._storage[fkey] !== 'undefined'; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return true; } } return false; }, set: function(key, value) { var head = this._head, i = head, entry; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] !== 'undefined') { this._storage[fkey].value = value; return; } else { entry = this._storage[fkey] = new MapEntry(key, value); i = head.prev; // fall through } } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.value = value; return; } } entry = entry || new MapEntry(key, value); if (ES.SameValue(-0, key)) { entry.key = +0; // coerce -0 to +0 in entry } entry.next = this._head; entry.prev = this._head.prev; entry.prev.next = entry; entry.next.prev = entry; this._size += 1; }, 'delete': function(key) { var head = this._head, i = head; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] === 'undefined') { return false; } i = this._storage[fkey].prev; delete this._storage[fkey]; // fall through } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.key = i.value = empty; i.prev.next = i.next; i.next.prev = i.prev; this._size -= 1; return true; } } return false; }, clear: function() { this._size = 0; this._storage = emptyObject(); var head = this._head, i = head, p = i.next; while ((i = p) !== head) { i.key = i.value = empty; p = i.next; i.next = i.prev = head; } head.next = head.prev = head; }, keys: function() { return new MapIterator(this, "key"); }, values: function() { return new MapIterator(this, "value"); }, entries: function() { return new MapIterator(this, "key+value"); }, forEach: function(callback) { var context = arguments.length > 1 ? arguments[1] : null; var it = this.entries(); for (var entry = it.next(); !entry.done; entry = it.next()) { callback.call(context, entry.value[1], entry.value[0], this); } } }); addIterator(Map.prototype, function() { return this.entries(); }); return Map; })(), Set: (function() { // Creating a Map is expensive. To speed up the common case of // Sets containing only string or numeric keys, we use an object // as backing storage and lazily create a full Map only when // required. var SetShim = function Set(iterable) { var set = this; set = emulateES6construct(set); if (!set._es6set) { throw new TypeError('bad set'); } defineProperties(set, { '[[SetData]]': null, '_storage': emptyObject() }); // Optionally initialize map from iterable if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = set.add; if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; adder.call(set, nextItem); } } return set; }; var Set$prototype = SetShim.prototype; defineProperties(SetShim, { '@@create': function(obj) { var constructor = this; var prototype = constructor.prototype || Set$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6set: true }); return obj; } }); // Switch from the object backing storage to a full Map. var ensureMap = function ensureMap(set) { if (!set['[[SetData]]']) { var m = set['[[SetData]]'] = new collectionShims.Map(); Object.keys(set._storage).forEach(function(k) { // fast check for leading '$' if (k.charCodeAt(0) === 36) { k = k.slice(1); } else { k = +k; } m.set(k, k); }); set._storage = null; // free old backing storage } }; Object.defineProperty(SetShim.prototype, 'size', { configurable: true, enumerable: false, get: function() { if (typeof this._storage === 'undefined') { // https://github.com/paulmillr/es6-shim/issues/176 throw new TypeError('size method called on incompatible Set'); } ensureMap(this); return this['[[SetData]]'].size; } }); defineProperties(SetShim.prototype, { has: function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return !!this._storage[fkey]; } ensureMap(this); return this['[[SetData]]'].has(key); }, add: function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { this._storage[fkey]=true; return; } ensureMap(this); return this['[[SetData]]'].set(key, key); }, 'delete': function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { delete this._storage[fkey]; return; } ensureMap(this); return this['[[SetData]]']['delete'](key); }, clear: function() { if (this._storage) { this._storage = emptyObject(); return; } return this['[[SetData]]'].clear(); }, keys: function() { ensureMap(this); return this['[[SetData]]'].keys(); }, values: function() { ensureMap(this); return this['[[SetData]]'].values(); }, entries: function() { ensureMap(this); return this['[[SetData]]'].entries(); }, forEach: function(callback) { var context = arguments.length > 1 ? arguments[1] : null; var entireSet = this; ensureMap(this); this['[[SetData]]'].forEach(function(value, key) { callback.call(context, key, key, entireSet); }); } }); addIterator(SetShim.prototype, function() { return this.values(); }); return SetShim; })() }; defineProperties(globals, collectionShims); if (globals.Map || globals.Set) { /* - In Firefox < 23, Map#size is a function. - In all current Firefox, Set#entries/keys/values & Map#clear do not exist - https://bugzilla.mozilla.org/show_bug.cgi?id=869996 - In Firefox 24, Map and Set do not implement forEach - In Firefox 25 at least, Map and Set are callable without "new" */ if ( typeof globals.Map.prototype.clear !== 'function' || new globals.Set().size !== 0 || new globals.Map().size !== 0 || typeof globals.Map.prototype.keys !== 'function' || typeof globals.Set.prototype.keys !== 'function' || typeof globals.Map.prototype.forEach !== 'function' || typeof globals.Set.prototype.forEach !== 'function' || isCallableWithoutNew(globals.Map) || isCallableWithoutNew(globals.Set) || !supportsSubclassing(globals.Map, function(M) { return (new M([])) instanceof M; }) ) { globals.Map = collectionShims.Map; globals.Set = collectionShims.Set; } } // Shim incomplete iterator implementations. addIterator(Object.getPrototypeOf((new globals.Map()).keys())); addIterator(Object.getPrototypeOf((new globals.Set()).keys())); } }; main(); // CommonJS and <script> });
test/app/containers/App.spec.js
jordanco/drafter-frontend
import React from 'react'; import expect from 'expect'; import { mount } from 'enzyme'; import { createStore, combineReducers, applyMiddleware, compose } from 'redux'; import thunk from 'redux-thunk'; import { Provider } from 'react-redux'; import App from '../../../src/app/containers/App'; // import configureStore from '../../../src/app/store/configureStore'; import counter from '../../../src/app/reducers/counter'; function configureStore(initialState) { const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); return createStoreWithMiddleware(combineReducers({ counter }), initialState); } describe('containers', () => { describe('App', () => { it('should display initial count', () => { const wrapper = mount(<Provider store={ configureStore() }><App /></Provider>); expect(wrapper.find('span.counter').text()).toBe('0'); }); [ { title: 'should display updated count after increment button click', result: '1' }, { title: 'should display updated count after decrement button click', result: '-1' }, { title: 'shouldnt change if even and if odd button clicked', result: '0' }, { idx: 2, title: 'should change if odd and if odd button clicked', value: { counter: { count: 1 } }, result: '2' } ] .forEach((rule, idx) => { it(rule.title, () => { const wrapper = mount(<Provider store={ configureStore(rule.value) }><App /></Provider>); wrapper.find('button').at(rule.idx || idx).simulate('click'); expect(wrapper.find('span.counter').text()).toEqual(rule.result); }); }); }); });
packages/material-ui-icons/src/Toll.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M15 4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z" /><path d="M3 12c0-2.61 1.67-4.83 4-5.65V4.26C3.55 5.15 1 8.27 1 12s2.55 6.85 6 7.74v-2.09c-2.33-.82-4-3.04-4-5.65z" /></React.Fragment> , 'Toll');
src/mobile/NewsMobile.js
qingweibinary/binary-next-gen
import React, { Component } from 'react'; import Tabs from '../_common/Tabs'; import MobilePage from '../containers/MobilePage'; import NewsContainer from '../news/NewsContainer'; import VideoListContainer from '../video/VideoListContainer'; export default class NewsMobile extends Component { constructor(props) { super(props); this.state = { activeTab: 0 }; } render() { const tabs = [ { text: 'Daily Report', component: <NewsContainer /> }, { text: 'Binary TV', component: <VideoListContainer /> }, ]; return ( <MobilePage> <Tabs id="settings" activeIndex={this.state.activeTab} onChange={idx => this.setState({ activeTab: idx })} tabs={tabs} /> </MobilePage> ); } }
src/setupTests.js
mdcarter/lunchfinder.io
import 'raf/polyfill'; import React from 'react'; import { configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import PlacesAutocomplete, { geocodeByAddress, getLatLng } from 'react-places-autocomplete'; import GoogleMapReact from 'google-map-react'; configure({ adapter: new Adapter() }); jest.mock('google-map-react'); GoogleMapReact.mockImplementation(() => { return { render: () => { return <div className="google-map-react" />; } }; }); jest.mock('react-places-autocomplete'); PlacesAutocomplete.mockImplementation(() => { return { render: () => { return <div className="react-places-autocomplete" />; } }; }); geocodeByAddress.mockImplementation(() => { return new Promise(resolve => { resolve(['address']); }); }); getLatLng.mockImplementation(() => { return new Promise(resolve => { resolve({ lat: 1, lng: 2 }); }); }); window.fetch = jest.fn().mockImplementation(() => Promise.resolve({ json: () => [] }));
ajax/libs/yui/3.4.1/simpleyui/simpleyui.js
Amomo/cdnjs
/** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** * The YUI global namespace object. If YUI is already defined, the * existing YUI object will not be overwritten so that defined * namespaces are preserved. It is the constructor for the object * the end user interacts with. As indicated below, each instance * has full custom event support, but only if the event system * is available. This is a self-instantiable factory function. You * can invoke it directly like this: * * YUI().use('*', function(Y) { * // ready * }); * * But it also works like this: * * var Y = YUI(); * * @class YUI * @constructor * @global * @uses EventTarget * @param o* {object} 0..n optional configuration objects. these values * are store in Y.config. See <a href="config.html">Config</a> for the list of supported * properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); // YUI.GlobalConfig is a master configuration that might span // multiple contexts in a non-browser environment. It is applied // first to all instances in all contexts. if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } // YUI_Config is a page-level config. It is applied to all // instances created on the page. This is applied after // YUI.GlobalConfig, and before the instance level configuration // objects. if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', DOC_LABEL = 'yui3-js-enabled', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.3.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {object} the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, rls = config.rls, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (rls && name == 'rls') { clobber(rls, attr); } else if (name == 'win') { config[name] = attr.contentWindow || attr; config.doc = config[name].document; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** * Old way to apply a config to the instance (calls `applyConfig` under the hood) * @private * @method _config * @param {Object} o The config to apply */ _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private * @method _init */ _init: function() { var filter, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-rls" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-rls/yui-rls.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path } } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/\./g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { win: win, doc: doc, debug: true, useBrowserConsole: true, throwFail: true, bootstrap: true, cacheUse: true, fetchCSS: true, use_rls: false, rls_timeout: 2000 }; if (YUI.Env.rls_disabled) { Y.config.use_rls = false; } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later']; for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {String} the YUI instance id. * @param method {String} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {Object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m.apply(instance, args); } return null; }, /** * Registers a module with the YUI global. The easiest way to create a * first-class YUI module is to use the YUI component build tool. * * http://yuilibrary.com/projects/builder * * The build system will produce the `YUI.add` wrapper for you module, along * with any configuration info required for the module. * @method add * @param name {String} module name. * @param fn {Function} entry point into the module that * is used to bind module to the YUI instance. * @param version {String} version string. * @param details {Object} optional config data: * @param details.requires {Array} features that must be present before this module can be attached. * @param details.optional {Array} optional features that should be present if loadOptional * is defined. Note: modules are not often loaded this way in YUI 3, * but this field is still useful to inform the user that certain * features in the component will require additional dependencies. * @param details.use {Array} features that are included within this module which need to * be attached automatically when this module is attached. This * supports the YUI 3 rollup system -- a module with submodules * defined will need to have the submodules listed in the 'use' * config. The YUI component build tool does this for you. * @return {YUI} the YUI instance. * */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, loader, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { loader = instances[i].Env._loader; if (loader) { if (!loader.moduleInfo[name]) { loader.addModule(details, name); } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @method _attach * @private */ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, done = Y.Env._attached, len = r.length, loader; //console.info('attaching: ' + r, 'info', 'yui'); for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name]) { Y._attach(aliases[name]); continue; } if (!mod) { loader = Y.Env._loader; if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; if (mod.use) { moot = true; } } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot) { if (name.indexOf('skin-') === -1) { Y.Env._missed.push(name); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } details = mod.details; req = details.requires; use = details.use; after = details.after; if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * * All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * * Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * * Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * * Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @method use * @param modules* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * * @example * // loads and attaches dd and its dependencies * YUI().use('dd', function(Y) {}); * * // loads and attaches dd and node as well as all of their dependencies (since 3.4.0) * YUI().use(['dd', 'node'], function(Y) {}); * * // attaches all modules that are available on the page * YUI().use('*', function(Y) {}); * * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) {}); * * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) {}); * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** * Notify handler from Loader for attachment/load errors * @method _notify * @param callback {Function} The callback to pass to the `Y.config.loadErrorFn` * @param response {Object} The response returned from Loader * @param args {Array} The aruments passed from Loader * @private */ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } }, /** * This private method is called from the `use` method queue. To ensure that only one set of loading * logic is performed at a time. * @method _use * @private * @param args* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. */ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, handleRLS, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { if (!names.length) { return; } YArray.each(names, function(name) { // add this module to full list of things to attach if (!skip) { r.push(name); } // only attach a module once if (used[name]) { return; } var m = mods[name], req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } }); }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if (missing.sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = false; Y._use(args, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { ret = Y._attach(Y.Object.keys(mods)); if (ret) { handleLoader(); } return Y; } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; } // process each requirement and any additional requirements // the module metadata specifies process(args); len = missing.length; if (len) { missing = Y.Object.keys(YArray.hash(missing)); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(args); loader.insert(null, (fetchCSS) ? null : 'js'); // loader.partial(missing, (fetchCSS) ? null : 'js'); } else if (len && Y.config.use_rls && !YUI.Env.rls_enabled) { G_ENV._rls_queue = G_ENV._rls_queue || new Y.Queue(); // server side loader service handleRLS = function(instance, argz) { var rls_end = function(o) { handleLoader(o); instance.rls_advance(); }, rls_url = instance._rls(argz); if (rls_url) { instance.rls_oncomplete(function(o) { rls_end(o); }); instance.Get.script(rls_url, { data: argz, timeout: instance.config.rls_timeout, onFailure: instance.rls_handleFailure, onTimeout: instance.rls_handleTimeout }); } else { rls_end({ data: argz }); } }; G_ENV._rls_queue.add(function() { G_ENV._rls_in_progress = true; Y.rls_callback = callback; Y.rls_locals(Y, args, handleRLS); }); if (!G_ENV._rls_in_progress && G_ENV._rls_queue.size()) { G_ENV._rls_queue.next()(); } } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** * Returns the namespace specified and creates it if it doesn't exist * * YUI.namespace("property.package"); * YUI.namespace("YAHOO.property.package"); * * Either of the above would create `YUI.property`, then * `YUI.property.package` (`YAHOO` is scrubbed out, this is * to remain compatible with YUI2) * * Be careful when naming packages. Reserved words may work in some browsers * and not others. For instance, the following will fail in Safari: * * YUI.namespace("really.long.nested.namespace"); * * This fails because "long" is a future reserved word in ECMAScript * * @method namespace * @param {string*} arguments 1-n namespaces to create. * @return {object} A reference to the last namespace object created. */ namespace: function() { var a = arguments, o = this, i = 0, j, d, arg; for (; i < a.length; i++) { // d = ('' + a[i]).split('.'); arg = a[i]; if (arg.indexOf(PERIOD)) { d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** * Report an error. The reporting mechanism is controled by * the `throwFail` configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown * @method error * @param msg {String} the error message. * @param e {Error|String} Optional JS error that was caught, or an error string. * @param data Optional additional info * and `throwFail` is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, data) { var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (Y.config.throwFail && !ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error'); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {String} optional guid prefix. * @return {String} the guid. */ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a `guid` associated with an object. If the object * does not have one, a new one is created unless `readOnly` * is specified. * @method stamp * @param o {Object} The object to stamp. * @param readOnly {Boolean} if `true`, a valid guid will only * be returned if the object has one assigned to it. * @return {String} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the `YUI` instance. This object is supplied by the implementer * when instantiating a `YUI` instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * `applyConfig()` to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the `domready` custom event. * * @property injected * @type boolean * @default false */ /** * If `throwFail` is set, `Y.error` will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default). * * @property core * @type string[] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in `DataType.Date.format()` instead. */ /** * The default locale * @property locale * @type string * @deprecated use `config.lang` instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because removing the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?` * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * For dynamic loading. * * @property filter * @type string|object */ /** * The `skin` config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the `use()` method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. See `Loader.addModule` for the supported module * metadata fields. Also see groups, which provides a way to * configure the base and combo spec for a set of modules. * * modules: { * mymod1: { * requires: ['node'], * fullpath: 'http://myserver.mydomain.com/mymod1/mymod1.js' * }, * mymod2: { * requires: ['mymod1'], * fullpath: 'http://myserver.mydomain.com/mymod2/mymod2.js' * } * } * * @property modules * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. * * groups: { * yui2: { * // specify whether or not this group has a combo service * combine: true, * * // the base path for non-combo paths * base: 'http://yui.yahooapis.com/2.8.0r4/build/', * * // the path to the combo service * comboBase: 'http://yui.yahooapis.com/combo?', * * // a fragment to prepend to the path attribute when * // when building combo urls * root: '2.8.0r4/build/', * * // the module definitions * modules: { * yui2_yde: { * path: "yahoo-dom-event/yahoo-dom-event.js" * }, * yui2_anim: { * path: "animation/animation.js", * requires: ['yui2_yde'] * } * } * } * } * * @property groups * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.8.1 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 1 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true * @deprecated no longer used */ /** * The parameter defaults for the remote loader service. * Requires the rls submodule. The properties that are * supported: * * * `m`: comma separated list of module requirements. This * must be the param name even for custom implemetations. * * `v`: the version of YUI to load. Defaults to the version * of YUI that is being used. * * `gv`: the version of the gallery to load (see the gallery config) * * `env`: comma separated list of modules already on the page. * this must be the param name even for custom implemetations. * * `lang`: the languages supported on the page (see the lang config) * * `'2in3v'`: the version of the 2in3 wrapper to use (see the 2in3 config). * * `'2v'`: the version of yui2 to use in the yui 2in3 wrappers * * `filt`: a filter def to apply to the urls (see the filter config). * * `filts`: a list of custom filters to apply per module * * `tests`: this is a map of conditional module test function id keys * with the values of 1 if the test passes, 0 if not. This must be * the name of the querystring param in custom templates. * * @since 3.2.0 * @property rls */ /** * The base path to the remote loader service * * @since 3.2.0 * @property rls_base */ /** * The template to use for building the querystring portion * of the remote loader service url. The default is determined * by the rls config -- each property that has a value will be * represented. * * @since 3.2.0 * @property rls_tmpl * @example * m={m}&v={v}&env={env}&lang={lang}&filt={filt}&tests={tests} * */ /** * Configure the instance to use a remote loader service instead of * the client loader. * * @since 3.2.0 * @property use_rls */ YUI.add('yui-base', function(Y) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementation. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype); /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = (!unsafeNatives && Array.isArray) || function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * <p> * Returns a string representing the type of the item passed in. * </p> * * <p> * Known issues: * </p> * * <ul> * <li> * <code>typeof HTMLElementCollection</code> returns function in Safari, but * <code>Y.type()</code> reports object, which could be a good thing -- * but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. * </li> * </ul> * * @method type * @param o the item to test. * @return {string} the detected type. * @static */ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * * @module yui * @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or alert (window), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Native.forEach ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Native.indexOf ? function (array, value) { // TODO: support fromIndex return Native.indexOf.call(array, value); } : function (array, value) { for (var i = 0, len = array.length; i < len; ++i) { if (array[i] === value) { return i; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Native.some ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : arg.toString(); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var args = arguments, i = 0, len = args.length, result = {}; for (; i < len; ++i) { Y.mix(result, args[i], true); } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties will not be overwritten or merged unless the _overwrite_ or _merge_ parameters are `true`, respectively. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Int} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a call // to `hasOwnProperty` on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } exists = alwaysOverwrite ? false : hasOwn.call(to, key); if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } exists = alwaysOverwrite ? false : hasOwn.call(to, key); if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var hasOwn = Object.prototype.hasOwnProperty, // If either MooTools or Prototype is on the page, then there's a chance that we // can't trust "native" language features to actually be native. When this is // the case, we take the safe route and fall back to our own non-native // implementations. win = Y.config.win, unsafeNatives = win && !!(win.MooTools || win.Prototype), UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = (!unsafeNatives && Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type {Boolean} * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = (!unsafeNatives && Object.keys) || function (obj) { if (!Y.Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; for (key in obj) { if (owns(obj, key)) { keys.push(key); } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { return O.keys(obj).length; }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Y.Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(obj).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method for parsing the UA string. Defaults to assigning it's value to Y.UA * @static * @method Env.parseUA * @param {String} subUA Parse this UA string instead of navigator.userAgent * @returns {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh/i).test(ua)) { o.os = 'macintosh'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; // Mobile browser check if (/ Mobile\//.test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } } m = ua.match(/Chrome\/([^\s]*)/); if (m && m[1]) { o.chrome = numberify(m[1]); // Chrome o.safari = 0; //Reset safari back to 0 } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } YUI.Env.UA = o; return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "app": ["controller","model","model-list","view"], "attribute": ["attribute-base","attribute-complex"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-base","datatable-datasource","datatable-sort","datatable-scroll"], "datatype": ["datatype-number","datatype-date","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-uievents","widget-skin"] }; }, '@VERSION@' ); YUI.add('get', function(Y) { /** * Provides a mechanism to fetch remote resources and * insert them into a document. * @module yui * @submodule get */ /** * Fetches and inserts one or more script or link nodes into the document * @class Get * @static */ var ua = Y.UA, L = Y.Lang, TYPE_JS = 'text/javascript', TYPE_CSS = 'text/css', STYLESHEET = 'stylesheet', SCRIPT = 'script', AUTOPURGE = 'autopurge', UTF8 = 'utf-8', LINK = 'link', ASYNC = 'async', ALL = true, // FireFox does not support the onload event for link nodes, so // there is no way to make the css requests synchronous. This means // that the css rules in multiple files could be applied out of order // in this browser if a later request returns before an earlier one. // Safari too. ONLOAD_SUPPORTED = { script: ALL, css: !(ua.webkit || ua.gecko) }, /** * hash of queues to manage multiple requests * @property queues * @private */ queues = {}, /** * queue index used to generate transaction ids * @property qidx * @type int * @private */ qidx = 0, /** * interal property used to prevent multiple simultaneous purge * processes * @property purging * @type boolean * @private */ purging, /** * Clear timeout state * * @method _clearTimeout * @param {Object} q Queue data * @private */ _clearTimeout = function(q) { var timer = q.timer; if (timer) { clearTimeout(timer); q.timer = null; } }, /** * Generates an HTML element, this is not appended to a document * @method _node * @param {string} type the type of element. * @param {Object} attr the fixed set of attribute for the type. * @param {Object} custAttrs optional Any custom attributes provided by the user. * @param {Window} win optional window to create the element in. * @return {HTMLElement} the generated node. * @private */ _node = function(type, attr, custAttrs, win) { var w = win || Y.config.win, d = w.document, n = d.createElement(type), i; if (custAttrs) { Y.mix(attr, custAttrs); } for (i in attr) { if (attr[i] && attr.hasOwnProperty(i)) { n.setAttribute(i, attr[i]); } } return n; }, /** * Generates a link node * @method _linkNode * @param {string} url the url for the css file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _linkNode = function(url, win, attributes) { return _node(LINK, { id: Y.guid(), type: TYPE_CSS, rel: STYLESHEET, href: url }, attributes, win); }, /** * Generates a script node * @method _scriptNode * @param {string} url the url for the script file. * @param {Window} win optional window to create the node in. * @param {object} attributes optional attributes collection to apply to the * new node. * @return {HTMLElement} the generated node. * @private */ _scriptNode = function(url, win, attributes) { return _node(SCRIPT, { id: Y.guid(), type: TYPE_JS, src: url }, attributes, win); }, /** * Returns the data payload for callback functions. * @method _returnData * @param {object} q the queue. * @param {string} msg the result message. * @param {string} result the status message from the request. * @return {object} the state data from the request. * @private */ _returnData = function(q, msg, result) { return { tId: q.tId, win: q.win, data: q.data, nodes: q.nodes, msg: msg, statusText: result, purge: function() { _purge(this.tId); } }; }, /** * The transaction is finished * @method _end * @param {string} id the id of the request. * @param {string} msg the result message. * @param {string} result the status message from the request. * @private */ _end = function(id, msg, result) { var q = queues[id], onEnd = q && q.onEnd; q.finished = true; if (onEnd) { onEnd.call(q.context, _returnData(q, msg, result)); } }, /** * The request failed, execute fail handler with whatever * was accomplished. There isn't a failure case at the * moment unless you count aborted transactions * @method _fail * @param {string} id the id of the request * @private */ _fail = function(id, msg) { var q = queues[id], onFailure = q.onFailure; _clearTimeout(q); if (onFailure) { onFailure.call(q.context, _returnData(q, msg)); } _end(id, msg, 'failure'); }, /** * Abort the transaction * * @method _abort * @param {Object} id * @private */ _abort = function(id) { _fail(id, 'transaction ' + id + ' was aborted'); }, /** * The request is complete, so executing the requester's callback * @method _complete * @param {string} id the id of the request. * @private */ _complete = function(id) { var q = queues[id], onSuccess = q.onSuccess; _clearTimeout(q); if (q.aborted) { _abort(id); } else { if (onSuccess) { onSuccess.call(q.context, _returnData(q)); } // 3.3.0 had undefined msg for this path. _end(id, undefined, 'OK'); } }, /** * Get node reference, from string * * @method _getNodeRef * @param {String|HTMLElement} nId The node id to find. If an HTMLElement is passed in, it will be returned. * @param {String} tId Queue id, used to determine document for queue * @private */ _getNodeRef = function(nId, tId) { var q = queues[tId], n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId; if (!n) { _fail(tId, 'target node not found: ' + nId); } return n; }, /** * Removes the nodes for the specified queue * @method _purge * @param {string} tId the transaction id. * @private */ _purge = function(tId) { var nodes, doc, parent, sibling, node, attr, insertBefore, i, l, q = queues[tId]; if (q) { nodes = q.nodes; l = nodes.length; // TODO: Why is node.parentNode undefined? Which forces us to do this... /* doc = q.win.document; parent = doc.getElementsByTagName('head')[0]; insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0]; if (insertBefore) { sibling = _getNodeRef(insertBefore, tId); if (sibling) { parent = sibling.parentNode; } } */ for (i = 0; i < l; i++) { node = nodes[i]; parent = node.parentNode; if (node.clearAttributes) { node.clearAttributes(); } else { // This destroys parentNode ref, so we hold onto it above first. for (attr in node) { if (node.hasOwnProperty(attr)) { delete node[attr]; } } } parent.removeChild(node); } } q.nodes = []; }, /** * Progress callback * * @method _progress * @param {string} id The id of the request. * @param {string} The url which just completed. * @private */ _progress = function(id, url) { var q = queues[id], onProgress = q.onProgress, o; if (onProgress) { o = _returnData(q); o.url = url; onProgress.call(q.context, o); } }, /** * Timeout detected * @method _timeout * @param {string} id the id of the request. * @private */ _timeout = function(id) { var q = queues[id], onTimeout = q.onTimeout; if (onTimeout) { onTimeout.call(q.context, _returnData(q)); } _end(id, 'timeout', 'timeout'); }, /** * onload callback * @method _loaded * @param {string} id the id of the request. * @return {string} the result. * @private */ _loaded = function(id, url) { var q = queues[id], sync = (q && !q.async); if (!q) { return; } if (sync) { _clearTimeout(q); } _progress(id, url); // TODO: Cleaning up flow to have a consistent end point // !q.finished check is for the async case, // where scripts may still be loading when we've // already aborted. Ideally there should be a single path // for this. if (!q.finished) { if (q.aborted) { _abort(id); } else { if ((--q.remaining) === 0) { _complete(id); } else if (sync) { _next(id); } } } }, /** * Detects when a node has been loaded. In the case of * script nodes, this does not guarantee that contained * script is ready to use. * @method _trackLoad * @param {string} type the type of node to track. * @param {HTMLElement} n the node to track. * @param {string} id the id of the request. * @param {string} url the url that is being loaded. * @private */ _trackLoad = function(type, n, id, url) { // TODO: Can we massage this to use ONLOAD_SUPPORTED[type]? // IE supports the readystatechange event for script and css nodes // Opera only for script nodes. Opera support onload for script // nodes, but this doesn't fire when there is a load failure. // The onreadystatechange appears to be a better way to respond // to both success and failure. if (ua.ie) { n.onreadystatechange = function() { var rs = this.readyState; if ('loaded' === rs || 'complete' === rs) { n.onreadystatechange = null; _loaded(id, url); } }; } else if (ua.webkit) { // webkit prior to 3.x is no longer supported if (type === SCRIPT) { // Safari 3.x supports the load event for script nodes (DOM2) n.addEventListener('load', function() { _loaded(id, url); }, false); } } else { // FireFox and Opera support onload (but not DOM2 in FF) handlers for // script nodes. Opera, but not FF, supports the onload event for link nodes. n.onload = function() { _loaded(id, url); }; n.onerror = function(e) { _fail(id, e + ': ' + url); }; } }, _insertInDoc = function(node, id, win) { // Add it to the head or insert it before 'insertBefore'. // Work around IE bug if there is a base tag. var q = queues[id], doc = win.document, insertBefore = q.insertBefore || doc.getElementsByTagName('base')[0], sibling; if (insertBefore) { sibling = _getNodeRef(insertBefore, id); if (sibling) { sibling.parentNode.insertBefore(node, sibling); } } else { // 3.3.0 assumed head is always around. doc.getElementsByTagName('head')[0].appendChild(node); } }, /** * Loads the next item for a given request * @method _next * @param {string} id the id of the request. * @return {string} the result. * @private */ _next = function(id) { // Assigning out here for readability var q = queues[id], type = q.type, attrs = q.attributes, win = q.win, timeout = q.timeout, node, url; if (q.url.length > 0) { url = q.url.shift(); // !q.timer ensures that this only happens once for async if (timeout && !q.timer) { q.timer = setTimeout(function() { _timeout(id); }, timeout); } if (type === SCRIPT) { node = _scriptNode(url, win, attrs); } else { node = _linkNode(url, win, attrs); } // add the node to the queue so we can return it in the callback q.nodes.push(node); _trackLoad(type, node, id, url); _insertInDoc(node, id, win); if (!ONLOAD_SUPPORTED[type]) { _loaded(id, url); } if (q.async) { // For sync, the _next call is chained in _loaded _next(id); } } }, /** * Removes processed queues and corresponding nodes * @method _autoPurge * @private */ _autoPurge = function() { if (purging) { return; } purging = true; var i, q; for (i in queues) { if (queues.hasOwnProperty(i)) { q = queues[i]; if (q.autopurge && q.finished) { _purge(q.tId); delete queues[i]; } } } purging = false; }, /** * Saves the state for the request and begins loading * the requested urls * @method queue * @param {string} type the type of node to insert. * @param {string} url the url to load. * @param {object} opts the hash of options for this request. * @return {object} transaction object. * @private */ _queue = function(type, url, opts) { opts = opts || {}; var id = 'q' + (qidx++), thresh = opts.purgethreshold || Y.Get.PURGE_THRESH, q; if (qidx % thresh === 0) { _autoPurge(); } // Merge to protect opts (grandfathered in). q = queues[id] = Y.merge(opts); // Avoid mix, merge overhead. Known set of props. q.tId = id; q.type = type; q.url = url; q.finished = false; q.nodes = []; q.win = q.win || Y.config.win; q.context = q.context || q; q.autopurge = (AUTOPURGE in q) ? q.autopurge : (type === SCRIPT) ? true : false; q.attributes = q.attributes || {}; q.attributes.charset = opts.charset || q.attributes.charset || UTF8; if (ASYNC in q && type === SCRIPT) { q.attributes.async = q.async; } q.url = (L.isString(q.url)) ? [q.url] : q.url; // TODO: Do we really need to account for this developer error? // If the url is undefined, this is probably a trailing comma problem in IE. if (!q.url[0]) { q.url.shift(); } q.remaining = q.url.length; _next(id); return { tId: id }; }; Y.Get = { /** * The number of request required before an automatic purge. * Can be configured via the 'purgethreshold' config * @property PURGE_THRESH * @static * @type int * @default 20 * @private */ PURGE_THRESH: 20, /** * Abort a transaction * @method abort * @static * @param {string|object} o Either the tId or the object returned from * script() or css(). */ abort : function(o) { var id = (L.isString(o)) ? o : o.tId, q = queues[id]; if (q) { q.aborted = true; } }, /** * Fetches and inserts one or more script nodes into the head * of the current document or the document in a specified window. * * @method script * @static * @param {string|string[]} url the url or urls to the script(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the script(s) are finished loading * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onTimeout</dt> * <dd> * callback to execute when a timeout occurs. * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onEnd</dt> * <dd>a function that executes when the transaction finishes, * regardless of the exit path</dd> * <dt>onFailure</dt> * <dd> * callback to execute when the script load operation fails * The callback receives an object back with the following * data: * <dl> * <dt>win</dt> * <dd>the window the script(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted successfully</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove any nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading * (useful when passing in an array of js files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> * property, which identifies the file which was loaded.</dd> * <dt>async</dt> * <dd> * <p>When passing in an array of JS files, setting this flag to true * will insert them into the document in parallel, as opposed to the * default behavior, which is to chain load them serially. It will also * set the async attribute on the script node to true.</p> * <p>Setting async:true * will lead to optimal file download performance allowing the browser to * download multiple scripts in parallel, and execute them as soon as they * are available.</p> * <p>Note that async:true does not guarantee execution order of the * scripts being downloaded. They are executed in whichever order they * are received.</p> * </dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>autopurge</dt> * <dd> * setting to true will let the utilities cleanup routine purge * the script once loaded * </dd> * <dt>purgethreshold</dt> * <dd> * The number of transaction before autopurge should be initiated * </dd> * <dt>data</dt> * <dd> * data that is supplied to the callback when the script(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling. * If this is not specified, nodes will be inserted before a base * tag should it exist. Otherwise, the nodes will be appended to the * end of the document head.</dd> * </dl> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * <dt>timeout</dt> * <dd>Number of milliseconds to wait before aborting and firing * the timeout event</dd> * <pre> * &nbsp; Y.Get.script( * &nbsp; ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js", * &nbsp; "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"], * &nbsp; &#123; * &nbsp; onSuccess: function(o) &#123; * &nbsp; this.log("won't cause error because Y is the context"); * &nbsp; // immediately * &nbsp; &#125;, * &nbsp; onFailure: function(o) &#123; * &nbsp; &#125;, * &nbsp; onTimeout: function(o) &#123; * &nbsp; &#125;, * &nbsp; data: "foo", * &nbsp; timeout: 10000, // 10 second timeout * &nbsp; context: Y, // make the YUI instance * &nbsp; // win: otherframe // target another window/frame * &nbsp; autopurge: true // allow the utility to choose when to * &nbsp; // remove the nodes * &nbsp; purgetheshold: 1 // purge previous transaction before * &nbsp; // next transaction * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ script: function(url, opts) { return _queue(SCRIPT, url, opts); }, /** * Fetches and inserts one or more css link nodes into the * head of the current document or the document in a specified * window. * @method css * @static * @param {string} url the url or urls to the css file(s). * @param {object} opts Options: * <dl> * <dt>onSuccess</dt> * <dd> * callback to execute when the css file(s) are finished loading * The callback receives an object back with the following * data: * <dl>win</dl> * <dd>the window the link nodes(s) were inserted into</dd> * <dt>data</dt> * <dd>the data object passed in when the request was made</dd> * <dt>nodes</dt> * <dd>An array containing references to the nodes that were * inserted</dd> * <dt>purge</dt> * <dd>A function that, when executed, will remove the nodes * that were inserted</dd> * <dt> * </dl> * </dd> * <dt>onProgress</dt> * <dd>callback to execute when each individual file is done loading (useful when passing in an array of css files). Receives the same * payload as onSuccess, with the addition of a <code>url</code> property, which identifies the file which was loaded. Currently only useful for non Webkit/Gecko browsers, * where onload for css is detected accurately.</dd> * <dt>async</dt> * <dd>When passing in an array of css files, setting this flag to true will insert them * into the document in parallel, as oppposed to the default behavior, which is to chain load them (where possible). * This flag is more useful for scripts currently, since for css Get only chains if not Webkit/Gecko.</dd> * <dt>context</dt> * <dd>the execution context for the callbacks</dd> * <dt>win</dt> * <dd>a window other than the one the utility occupies</dd> * <dt>data</dt> * <dd> * data that is supplied to the callbacks when the nodes(s) are * loaded. * </dd> * <dt>insertBefore</dt> * <dd>node or node id that will become the new node's nextSibling</dd> * <dt>charset</dt> * <dd>Node charset, default utf-8 (deprecated, use the attributes * config)</dd> * <dt>attributes</dt> * <dd>An object literal containing additional attributes to add to * the link tags</dd> * </dl> * <pre> * Y.Get.css("http://localhost/css/menu.css"); * </pre> * <pre> * &nbsp; Y.Get.css( * &nbsp; ["http://localhost/css/menu.css", * &nbsp; insertBefore: 'custom-styles' // nodes will be inserted * &nbsp; // before the specified node * &nbsp; &#125;);. * </pre> * @return {tId: string} an object containing info about the * transaction. */ css: function(url, opts) { return _queue('css', url, opts); } }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; Y.mix(Y.namespace('Features'), { tests: feature_tests, add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // graphics-svg.js add('load', '0', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // ie-base-test.js add('load', '1', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-vml.js add('load', '2', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // ie-style-test.js add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // transition-test.js add('load', '4', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // 0 add('load', '5', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // autocomplete-list-keys-sniff.js add('load', '6', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-canvas.js add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // dd-gestures-test.js add('load', '8', { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }); // selector-test.js add('load', '9', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // history-hash-ie-test.js add('load', '10', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('intl-base', function(Y) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui-later', function(Y) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : data; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('yui', function(Y){}, '@VERSION@' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later']}); YUI.add('oop', function(Y) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Applies object properties from the supplier to the receiver. If * the target has the property, and the property is an object, the target * object will be augmented with the supplier's value. If the property * is an array, the suppliers value will be appended to the target. * @method aggregate * @param {function} r the object to receive the augmentation. * @param {function} s the object that supplies the properties to augment. * @param {boolean} ov if true, properties already on the receiver * will be overwritten if found on the supplier. * @param {string[]} wl a whitelist. If supplied, only properties in * this list will be applied to the receiver. * @return {object} the extended object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** * Deep object/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; Y.mix(Y.namespace('Features'), { tests: feature_tests, add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // graphics-svg.js add('load', '0', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc; return (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, "trigger": "graphics" }); // ie-base-test.js add('load', '1', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-vml.js add('load', '2', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // ie-style-test.js add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // transition-test.js add('load', '4', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // 0 add('load', '5', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // autocomplete-list-keys-sniff.js add('load', '6', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-canvas.js add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (canvas && canvas.getContext && canvas.getContext("2d"))); }, "trigger": "graphics" }); // dd-gestures-test.js add('load', '8', { "name": "dd-gestures", "test": function(Y) { return (Y.config.win && ('ontouchstart' in Y.config.win && !Y.UA.chrome)); }, "trigger": "dd-drag" }); // selector-test.js add('load', '9', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // history-hash-ie-test.js add('load', '10', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('dom-core', function(Y) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf) { var ancestor = Y_DOM.ancestor.apply(Y_DOM, arguments), ret = (ancestor) ? [ancestor] : []; while ((ancestor = Y_DOM.ancestor(ancestor, fn))) { if (ancestor) { ret.unshift(ancestor); } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS]) { if (Y.UA.opera || needle[NODE_TYPE] === 1) { // IE & SAF contains fail if needle not an ELEMENT_NODE ret = element[CONTAINS](needle); } else { ret = Y_DOM._bruteContains(element, needle); } } else if (element[COMPARE_DOCUMENT_POSITION]) { // gecko if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.alert && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, wrap: function(node, html) { var parent = Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@' ,{requires:['oop','features']}); YUI.add('dom-base', function(Y) { var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttibute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } } } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (where.nodeType) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': nodeParent.insertBefore(newNode, node); break; case 'after': if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } break; default: node.appendChild(newNode); } } } else if (newNode) { node.appendChild(newNode); } return ret; } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = frag.children.tags('tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; } creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Int} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Int} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@' ,{requires:['dom-core']}); YUI.add('dom-style', function(Y) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT]; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { val = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null)[att]; } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@' ,{requires:['dom-base']}); YUI.add('dom-style-ie', function(Y) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@' ,{requires:['dom-style']}); YUI.add('dom-screen', function(Y) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, box, off1, off2, bLeft, bTop, mode, doc, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; rootNode = doc[DOCUMENT_ELEMENT]; // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (Y.UA.ie) { off1 = 2; off2 = 2; mode = doc[COMPAT_MODE]; bLeft = Y_DOM[GET_COMPUTED_STYLE](doc[DOCUMENT_ELEMENT], BORDER_LEFT_WIDTH); bTop = Y_DOM[GET_COMPUTED_STYLE](doc[DOCUMENT_ELEMENT], BORDER_TOP_WIDTH); if (Y.UA.ie === 6) { if (mode !== _BACK_COMPAT) { off1 = 0; off2 = 0; } } if ((mode == _BACK_COMPAT)) { if (bLeft !== MEDIUM) { off1 = parseInt(bLeft, 10); } if (bTop !== MEDIUM) { off2 = parseInt(bTop, 10); } } xy[0] -= off1; xy[1] -= off2; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; } } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Int} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Int} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Int} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Int} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passes nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance i.e. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node2 The node to get the region from or an Object literal of the region * $param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance i.e. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance i.e. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@' ,{requires:['dom-base', 'dom-style']}); YUI.add('selector-native', function(Y) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _foundCache: [], useNative: true, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { var groups = selector.split(','), queries = [], prefix = '', i, len; if (node) { // enforce for element scoping if (node.tagName) { node.id = node.id || Y.guid(); prefix = '[id="' + node.id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; if (!node.id) { node.id = Y.guid(); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + node.id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@' ,{requires:['dom-base']}); YUI.add('selector', function(Y) { }, '@VERSION@' ,{requires:['selector-native']}); YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property Do.originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property Do.currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ onceAfter: function() { var args = YArray(arguments, 0, true); args[0] = AFTER_PREFIX + args[0]; return this.once.apply(this, args); }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {string} type the type * @param {string} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('drag:drophit', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * Listen for an event one time. Equivalent to <code>on</code>, except that * the listener is immediately detached when executed. * @see on * @method once * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']}); YUI.add('event-custom-complex', function(Y) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || EMPTY; this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property type * @type string */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.extend(Y.EventFacade, Object, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret, events, subs, postponed, self = this, host = self.host || self, next, oldbubble; if (self.stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != self.stack.next.type) { self.log('queue ' + self.type); self.stack.queue.push([self, args]); return true; } } es = self.stack || { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; if (self.stoppedFn) { events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } // if (subCount) { if (subs[0]) { // self._procSubs(Y.merge(self.subscribers), args, ef); self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; // self.bubbling = true; es.bubbling = self.type; // if (host !== ef.target || es.type != self.type) { if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); // self.bubbling = false; es.bubbling = oldbubble; } if (self.prevented) { if (self.preventedFn) { self.preventedFn.apply(host, args); } } else if (self.defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { postponed = subs[1]; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } self.stack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, o2, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { o2 = {}; // protect the event facade properties Y.mix(o2, ef, true, FACADE_KEYS); // mix the data Y.mix(ef, o, true); // restore ef Y.mix(ef, o2, true, FACADE_KEYS); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } this.events.fire('stopped', this); }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } this.events.fire('stopped', this); }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = Y.Object.keys(FACADE); }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('node-core', function(Y) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Y.Node || HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Y.Node | Y.NodeList | any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && Y.instanceOf(args[0], Y_Node)) { args[0] = args[0]._node; } if (args[1] && Y.instanceOf(args[1], Y_Node)) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Y.Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Y.Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (Y.instanceOf(refNode, Y_Node)) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf) { return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf)); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf) { return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf)); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a Node instance of nodes based on the given CSS selector. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node} A Node instance for the matching HTMLElement. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Y.Node || HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && Y.instanceOf(a, Y_Node)) { a = a._node; } if (b && Y.instanceOf(b, Y_Node)) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, /** * @method getData * @description Retrieves arbitrary data stored on a Node instance. * This is not stored with the DOM node. * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { var ret; this._data = this._data || {}; if (arguments.length) { ret = this._data[name]; } else { ret = this._data; } return ret; }, /** * @method setData * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._data = this._data || {}; if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @description Clears stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (name) { delete this._data[name]; } else { delete this._data; } } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor */ var NodeList = function(nodes) { var tmp = []; if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (Y.instanceOf(nodes, Y.Node)) { nodes = [nodes._node]; } else if (Y.instanceOf(nodes[0], Y.Node)) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {Y.NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return Node a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Y.Node || DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** * Applies an event listener to each Node bound to the NodeList. * @method on * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @param {Object} context The context to call the handler with. * param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** Called on each Node instance * @method destroy * @see Node.destroy */ 'destroy', /** Called on each Node instance * @method empty * @see Node.empty */ 'empty', /** Called on each Node instance * @method remove * @see Node.remove */ 'remove', /** Called on each Node instance * @method set * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the first last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ 'removeAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@' ,{requires:['dom-core', 'selector']}); YUI.add('node-base', function(Y) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Y.Node | HTMLElement | Y.NodeList | HTMLCollection} content The content to insert * @param {Int | Y.Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Y.Node | HTMLElement} content The content to insert * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Y.Node | HTMLElement} content The content to insert * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Y.Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * @method setContent * @param {String | Y.Node | HTMLElement | Y.NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** Called on each Node instance * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** Called on each Node instance * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** Called on each Node instance * @method prepend * @see Node.prepend */ 'prepend', /** Called on each Node instance * @method setContent * @see Node.setContent */ 'setContent', /** Called on each Node instance * @method getContent * @see Node.getContent */ 'getContent' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i][TAG_NAME]) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** * Applies an event listener to each Node bound to the NodeList. * @method on * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @param {Object} context The context to call the handler with. * param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on * @for NodeList */ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {Object} Returns an event handle that can later be use to detach(). * @see Event.on */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll */ 'detachAll' ]); Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, toggleView: function(on, callback) { this._toggleView.apply(this, arguments); }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } }, '@VERSION@' ,{requires:['dom-base', 'node-core', 'event-base']}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function(Y) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event */ /** * The X location of the event on the page (including scroll) * @property pageX * @type int */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type int */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type int */ /** * The charCode for key events. Same as keyCode * @property charCode * @type int */ /** * The button that was pushed. * @property button * @type int */ /** * The button that was pushed. Same as button. * @property which * @type int */ /** * Node reference for the targeted element * @propery target * @type Node */ /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type int */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !o.alert); } catch(ex) { return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.subCount && !this.afterCount) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return Y.DOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); i = 0; len = children.length; for (; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } add(win, "unload", onUnload); Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); })(); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('pluginhost-base', function(Y) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config this[ns].setAttrs(config); } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namepsace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { this[ns].destroy(); delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {boolean} returns true, if the plugin has been plugged into this host, false otherwise. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('pluginhost-config', function(Y) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method Plugin.Host.plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method Plugin.Host.unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@' ,{requires:['pluginhost-base']}); YUI.add('event-delegate', function(Y) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param spec {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, context, filter, ...); // and Y.delegate(['click', 'key'], fn, context, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, context, filter) => // Y.delegate('click', fn, context, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** * Overrides the <code>_notify</code> method on the normal DOM subscription to * inject the filtering logic and only proceed in the case of a match. * * @method delegate.notifySub * @param thisObj {Object} default 'this' object for the callback * @param args {Array} arguments passed to the event's <code>fire()</code> * @param ce {CustomEvent} the custom event managing the DOM subscriptions for * the subscribed event on the subscribing node. * @return {Boolean} false if the event was stopped * @private * @static * @since 3.2.0 */ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** * <p>Compiles a selector string into a filter function to identify whether * Nodes along the parent axis of an event's target should trigger event * notification.</p> * * <p>This function is memoized, so previously compiled filter functions are * returned if the same selector string is provided.</p> * * <p>This function may be useful when defining synthetic events for delegate * handling.</p> * * @method delegate.compileFilter * @param selector {String} the selector string to base the filtration on * @return {Function} * @since 3.2.0 * @static */ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, e.currentTarget._node); }; }); /** * Walks up the parent axis of an event's target, and tests each element * against a supplied filter function. If any Nodes, including the container, * satisfy the filter, the delegated callback will be triggered for each. * * @method delegate._applyFilter * @param filter {Function} boolean function to test for inclusion in event * notification * @param args {Array} the arguments that would be passed to subscribers * @param ce {CustomEvent} the DOM event wrapper * @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter * @protected */ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ?null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@' ,{requires:['node-base']}); YUI.add('node-event-delegate', function(Y) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@' ,{requires:['node-base', 'event-delegate']}); YUI.add('node-pluginhost', function(Y) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); }; Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); }; }, '@VERSION@' ,{requires:['node-base', 'pluginhost']}); YUI.add('node-screen', function(Y) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config winHeight * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Y.Node || HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@' ,{requires:['node-base', 'dom-screen']}); YUI.add('node-style', function(Y) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ var methods = [ /** * Returns the style's current value. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ 'getStyle', /** * Returns the computed value for the given style property. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ 'getComputedStyle', /** * Sets a style property of the node. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ 'setStyle', /** * Sets multiple style properties on the node. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ 'setStyles' ]; Y.Node.importMethod(Y.DOM, methods); /** * Returns an array of values for each node. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); })(Y); }, '@VERSION@' ,{requires:['dom-style', 'node-base']}); YUI.add('querystring-stringify-simple', function(Y) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple * @for QueryString * @static */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; /** * <p>Converts a simple object to a Query String representation.</p> * <p>Nested objects, Arrays, and so on, are not supported.</p> * * @method stringify * @for QueryString * @public * @submodule querystring-stringify-simple * @param obj {Object} A single-level object to convert to a querystring. * @param cfg {Object} (optional) Configuration object. In the simple * module, only the arrayKey setting is * supported. When set to true, the key of an * array will have the '[]' notation appended * to the key;. * @static */ QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('io-base', function(Y) { /** * Base IO functionality. Provides basic XHR transport support. * @module io * @submodule io-base */ // Window reference var L = Y.Lang, // List of events that comprise the IO event lifecycle. E = ['start', 'complete', 'end', 'success', 'failure'], // Whitelist of used XHR response object properties. P = ['status', 'statusText', 'responseText', 'responseXML'], aH = 'getAllResponseHeaders', oH = 'getResponseHeader', w = Y.config.win, xhr = w.XMLHttpRequest, xdr = w.XDomainRequest, _i = 0; /** * The io class is a utility that brokers HTTP requests through a simplified * interface. Specifically, it allows JavaScript to make HTTP requests to * a resource without a page reload. The underlying transport for making * same-domain requests is the XMLHttpRequest object. YUI.io can also use * Flash, if specified as a transport, for cross-domain requests. * * @class IO * @constructor * @param {object} c - Object of EventTarget's publish method configurations * used to configure IO's events. */ function IO (c) { var io = this; io._uid = 'io:' + _i++; io._init(c); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * @description A counter that increments for each transaction. * * @property _id * @private * @type int */ _id: 0, /** * @description Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type object */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * @description Object that stores timeout values for any transaction with * a defined "timeout" configuration property. * * @property _timeout * @private * @type object */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(c) { var io = this, i; io.cfg = c || {}; Y.augment(io, Y.EventTarget); for (i = 0; i < 5; i++) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + E[i], Y.merge({ broadcast: 1 }, c)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + E[i], c); } }, /** * @description Method that creates a unique transaction object for each * request. * * @method _create * @private * @param {number} c - configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {number} i - transaction id * @return object */ _create: function(c, i) { var io = this, o = { id: L.isNumber(i) ? i : io._id++, uid: io._uid }, x = c.xdr, u = x ? x.use : c.form && c.form.upload ? 'iframe' : 'xhr', ie = (x && x.use === 'native' && xdr), t = io._transport; switch (u) { case 'native': case 'xhr': o.c = ie ? new xdr() : xhr ? new xhr() : new ActiveXObject('Microsoft.XMLHTTP'); o.t = ie ? true : false; break; default: o.c = t ? t[u] : {}; o.t = true; } return o; }, _destroy: function(o) { if (w) { if (xhr && o.t === true) { o.c.onreadystatechange = null; } else if (Y.UA.ie) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". o.c.abort(); } } o.c = null; o = null; }, /** * @description Method for creating and firing events. * * @method _evt * @private * @param {string} e - event to be published. * @param {object} o - transaction object. * @param {object} c - configuration data subset for event subscription. * * @return void */ _evt: function(e, o, c) { var io = this, a = c['arguments'], eF = io.cfg.emitFacade, // Use old-style parameters or use an Event Facade p = eF ? [{ id: o.id, data: o.c, cfg: c, arguments: a }] : [o.id], // IO Global events namespace. gE = "io:" + e, // IO Transaction events namespace. tE = "io-trn:" + e; if (!eF) { if (e === E[0] || e === E[2]) { if (a) { p.push(a); } } else { a ? p.push(o.c, a) : p.push(o.c); } } p.unshift(gE); io.fire.apply(io, p); if (c.on) { p[0] = tE; io.once(tE, c.on[e], c.context || Y); io.fire.apply(io, p); } }, /** * @description Fires event "io:start" and creates, fires a * transaction-specific start event, if config.on.start is * defined. * * @method start * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ start: function(o, c) { this._evt(E[0], o, c); }, /** * @description Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ complete: function(o, c) { this._evt(E[1], o, c); }, /** * @description Fires event "io:end" and creates, fires a * transaction-specific "end" event, if config.on.end is * defined. * * @method end * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ end: function(o, c) { this._evt(E[2], o, c); this._destroy(o); }, /** * @description Fires event "io:success" and creates, fires a * transaction-specific "success" event, if config.on.success is * defined. * * @method success * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ success: function(o, c) { this._evt(E[3], o, c); this.end(o, c); }, /** * @description Fires event "io:failure" and creates, fires a * transaction-specific "failure" event, if config.on.failure is * defined. * * @method failure * @public * @param {object} o - transaction object. * @param {object} c - configuration object for the transaction. * * @return void */ failure: function(o, c) { this._evt(E[4], o, c); this.end(o, c); }, /** * @description Retry an XDR transaction, using the Flash tranport, * if the native transport fails. * * @method _retry * @private * @param {object} o - Transaction object generated by _create(). * @param {string} uri - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * * @return void */ _retry: function(o, uri, c) { this._destroy(o); c.xdr.use = 'flash'; return this.send(uri, c, o.id); }, /** * @description Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {string} s - URI or root data. * @param {string} d - data to be concatenated onto URI. * @return int */ _concat: function(s, d) { s += (s.indexOf('?') === -1 ? '?' : '&') + d; return s; }, /** * @description Method that stores default client headers for all transactions. * If a label is passed with no value argument, the header will be deleted. * * @method _setHeader * @private * @param {string} l - HTTP header * @param {string} v - HTTP header value * @return int */ setHeader: function(l, v) { if (v) { this._headers[l] = v; } else { delete this._headers[l]; } }, /** * @description Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {object} o - XHR instance for the specific transaction. * @param {object} h - HTTP headers for the specific transaction, as defined * in the configuration object passed to YUI.io(). * @return void */ _setHeaders: function(o, h) { h = Y.merge(this._headers, h); Y.Object.each(h, function(v, p) { if (v !== 'disable') { o.setRequestHeader(p, h[p]); } }); }, /** * @description Starts timeout count if the configuration object * has a defined timeout property. * * @method _startTimeout * @private * @param {object} o - Transaction object generated by _create(). * @param {object} t - Timeout in milliseconds. * @return void */ _startTimeout: function(o, t) { var io = this; io._timeout[o.id] = w.setTimeout(function() { io._abort(o, 'timeout'); }, t); }, /** * @description Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {number} id - Transaction id. * @return void */ _clearTimeout: function(id) { w.clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * @description Method that determines if a transaction response qualifies * as success or failure, based on the response HTTP status code, and * fires the appropriate success or failure events. * * @method _result * @private * @static * @param {object} o - Transaction object generated by _create(). * @param {object} c - Configuration object passed to io(). * @return void */ _result: function(o, c) { var s = o.c.status; // IE reports HTTP 204 as HTTP 1223. if (s >= 200 && s < 300 || s === 1223) { this.success(o, c); } else { this.failure(o, c); } }, /** * @description Event handler bound to onreadystatechange. * * @method _rS * @private * @param {object} o - Transaction object generated by _create(). * @param {object} c - Configuration object passed to YUI.io(). * @return void */ _rS: function(o, c) { var io = this; if (o.c.readyState === 4) { if (c.timeout) { io._clearTimeout(o.id); } // Yield in the event of request timeout or abort. w.setTimeout(function() { io.complete(o, c); io._result(o, c); }, 0); } }, /** * @description Terminates a transaction due to an explicit abort or * timeout. * * @method _abort * @private * @param {object} o - Transaction object generated by _create(). * @param {string} s - Identifies timed out or aborted transaction. * * @return void */ _abort: function(o, s) { if (o && o.c) { o.e = s; o.c.abort(); } }, /** * @description Method for requesting a transaction. send() is implemented as * yui.io(). Each transaction may include a configuration object. Its * properties are: * * method: HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET. * * data: This is the name-value string that will be sent as the transaction * data. If the request is HTTP GET, the data become part of * querystring. If HTTP POST, the data are sent in the message body. * * xdr: Defines the transport to be used for cross-domain requests. By * setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. * The properties are: * { * use: Specify the transport to be used: 'flash' and 'native' * dataType: Set the value to 'XML' if that is the expected * response content type. * } * * * form: This is a defined object used to process HTML form as data. The * properties are: * { * id: Node object or id of HTML form. * useDisabled: Boolean value to allow disabled HTML form field * values to be sent as part of the data. * } * * on: This is a defined object used to create and handle specific * events during a transaction lifecycle. These events will fire in * addition to the global io events. The events are: * start - This event is fired when a request is sent to a resource. * complete - This event fires when the transaction is complete. * success - This event fires when the response status resolves to * HTTP 2xx. * failure - This event fires when the response status resolves to * HTTP 4xx, 5xx; and, for all transaction exceptions, * including aborted transactions and transaction timeouts. * end - This even is fired at the conclusion of the transaction * lifecycle, after a success or failure resolution. * * The properties are: * { * start: function(id, arguments){}, * complete: function(id, responseobject, arguments){}, * success: function(id, responseobject, arguments){}, * failure: function(id, responseobject, arguments){}, * end: function(id, arguments){} * } * Each property can reference a function or be written as an * inline function. * * sync: To enable synchronous transactions, set the configuration property * "sync" to true. Synchronous requests are limited to same-domain * requests only. * * context: Object reference for all defined transaction event handlers * when it is implemented as a method of a base object. Defining * "context" will set the reference of "this," used in the * event handlers, to the context value. In the case where * different event handlers all have different contexts, * use Y.bind() to set the execution context, instead. * * headers: This is a defined object of client headers, as many as * desired for this specific transaction. The object pattern is: * { 'header': 'value' }. * * timeout: This value, defined as milliseconds, is a time threshold for the * transaction. When this threshold is reached, and the transaction's * Complete event has not yet fired, the transaction will be aborted. * * arguments: User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" * and "end" event handlers. It is the third argument in the * "complete", "success", and "failure" event handlers. * * @method send * @private * @ * @param {string} uri - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * @param {number} i - transaction id, if already set. * @return object */ send: function(uri, c, i) { var o, m, r, s, d, io = this, u = uri; c = c ? Y.Object(c) : {}; o = io._create(c, i); m = c.method ? c.method.toUpperCase() : 'GET'; s = c.sync; d = c.data; // Serialize an object into a key-value string using // querystring-stringify-simple. if (L.isObject(d)) { d = Y.QueryString.stringify(d); } if (c.form) { if (c.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(o, uri, c); } else { // Serialize HTML form data into a key-value string. d = io._serialize(c.form, d); } } if (d) { switch (m) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, d); d = ''; break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' c.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, c.headers); break; } } if (o.t) { // Cross-domain request or custom transport configured. return io.xdr(u, o, c); } if (!s) { o.c.onreadystatechange = function() { io._rS(o, c); }; } try { // Determine if request is to be set as // synchronous or asynchronous. o.c.open(m, u, s ? false : true, c.username || null, c.password || null); io._setHeaders(o.c, c.headers || {}); io.start(o, c); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (c.xdr && c.xdr.credentials) { if (!Y.UA.ie) { o.c.withCredentials = true; } } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. o.c.send(d); if (s) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. r = Y.mix({ id: o.id, 'arguments': c['arguments'] }, o.c, false, P); r[aH] = function() { return o.c[aH](); }; r[oH] = function(h) { return o.c[oH](h); }; io.complete(o, c); io._result(o, c); return r; } } catch(e) { if (o.t) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(o, uri, c); } else { io.complete(o, c); io._result(o, c); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (c.timeout) { io._startTimeout(o, c.timeout); } return { id: o.id, abort: function() { return o.c ? io._abort(o, 'abort') : false; }, isInProgress: function() { return o.c ? o.c.readyState !== 4 && o.c.readyState !== 0 : false; }, io: io }; } }; /** * @description Method for requesting a transaction. * * @method io * @public * @static * @param {string} u - qualified path to transaction resource. * @param {object} c - configuration object for the transaction. * @return object */ Y.io = function(u, c) { // Calling IO through the static interface will use and reuse // an instance of IO. var o = Y.io._map['io:0'] || new IO(); return o.send.apply(o, [u, c]); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; }, '@VERSION@' ,{requires:['event-custom-base', 'querystring-stringify-simple']}); YUI.add('json-parse', function(Y) { /** * <p>The JSON module adds support for serializing JavaScript objects into * JSON strings and parsing JavaScript objects from strings in JSON format.</p> * * <p>The JSON namespace is added to your YUI instance including static methods * Y.JSON.parse(..) and Y.JSON.stringify(..).</p> * * <p>The functionality and method signatures follow the ECMAScript 5 * specification. In browsers with native JSON support, the native * implementation is used.</p> * * <p>The <code>json</code> module is a rollup of <code>json-parse</code> and * <code>json-stringify</code>.</p> * * <p>As their names suggest, <code>json-parse</code> adds support for parsing * JSON data (Y.JSON.parse) and <code>json-stringify</code> for serializing * JavaScript data into JSON strings (Y.JSON.stringify). You may choose to * include either of the submodules individually if you don't need the * complementary functionality, or include the rollup for both.</p> * * @module json * @class JSON * @static */ /** * Provides Y.JSON.parse method to accept JSON strings and return native * JavaScript objects. * * @module json * @submodule json-parse * @for JSON * @static */ // All internals kept private for security reasons function fromGlobal(ref) { return (Y.config.win || this || {})[ref]; } /** * Alias to native browser implementation of the JSON object if available. * * @property Native * @type {Object} * @private */ var _JSON = fromGlobal('JSON'), Native = (Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON), useNative = !!Native, /** * Replace certain Unicode characters that JavaScript may handle incorrectly * during eval--either by deleting them or treating them as line * endings--with escape sequences. * IMPORTANT NOTE: This regex will be used to modify the input if a match is * found. * * @property _UNICODE_EXCEPTIONS * @type {RegExp} * @private */ _UNICODE_EXCEPTIONS = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, /** * First step in the safety evaluation. Regex used to replace all escape * sequences (i.e. "\\", etc) with '@' characters (a non-JSON character). * * @property _ESCAPES * @type {RegExp} * @private */ _ESCAPES = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, /** * Second step in the safety evaluation. Regex used to replace all simple * values with ']' characters. * * @property _VALUES * @type {RegExp} * @private */ _VALUES = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, /** * Third step in the safety evaluation. Regex used to remove all open * square brackets following a colon, comma, or at the beginning of the * string. * * @property _BRACKETS * @type {RegExp} * @private */ _BRACKETS = /(?:^|:|,)(?:\s*\[)+/g, /** * Final step in the safety evaluation. Regex used to test the string left * after all previous replacements for invalid characters. * * @property _UNSAFE * @type {RegExp} * @private */ _UNSAFE = /[^\],:{}\s]/, /** * Replaces specific unicode characters with their appropriate \unnnn * format. Some browsers ignore certain characters during eval. * * @method escapeException * @param c {String} Unicode character * @return {String} the \unnnn escapement of the character * @private */ _escapeException = function (c) { return '\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4); }, /** * Traverses nested objects, applying a reviver function to each (key,value) * from the scope if the key:value's containing object. The value returned * from the function will replace the original value in the key:value pair. * If the value returned is undefined, the key will be omitted from the * returned object. * * @method _revive * @param data {MIXED} Any JavaScript data * @param reviver {Function} filter or mutation function * @return {MIXED} The results of the filtered data * @private */ _revive = function (data, reviver) { var walk = function (o,key) { var k,v,value = o[key]; if (value && typeof value === 'object') { for (k in value) { if (value.hasOwnProperty(k)) { v = walk(value, k); if (v === undefined) { delete value[k]; } else { value[k] = v; } } } } return reviver.call(o,key,value); }; return typeof reviver === 'function' ? walk({'':data},'') : data; }, /** * Parse a JSON string, returning the native JavaScript representation. * * @param s {string} JSON string data * @param reviver {function} (optional) function(k,v) passed each key value * pair of object literals, allowing pruning or altering values * @return {MIXED} the native JavaScript representation of the JSON string * @throws SyntaxError * @method parse * @static */ // JavaScript implementation in lieu of native browser support. Based on // the json2.js library from http://json.org _parse = function (s,reviver) { // Replace certain Unicode characters that are otherwise handled // incorrectly by some browser implementations. // NOTE: This modifies the input if such characters are found! s = s.replace(_UNICODE_EXCEPTIONS, _escapeException); // Test for any remaining invalid characters if (!_UNSAFE.test(s.replace(_ESCAPES,'@'). replace(_VALUES,']'). replace(_BRACKETS,''))) { // Eval the text into a JavaScript data structure, apply any // reviver function, and return return _revive( eval('(' + s + ')'), reviver ); } throw new SyntaxError('JSON.parse'); }; Y.namespace('JSON').parse = function (s,reviver) { if (typeof s !== 'string') { s += ''; } return Native && Y.JSON.useNativeParse ? Native.parse(s,reviver) : _parse(s,reviver); }; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( Native ) { try { useNative = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { useNative = false; } } /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeParse * @type Boolean * @default true * @static */ Y.JSON.useNativeParse = useNative; }, '@VERSION@' ); YUI.add('transition', function(Y) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', TRANSITION = 'transition', TRANSITION_CAMEL = 'Transition', TRANSITION_PROPERTY_CAMEL, TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, TRANSFORM_CAMEL, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + TRANSITION_CAMEL; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + TRANSITION_CAMEL; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; TRANSFORM_CAMEL = CAMEL_VENDOR_PREFIX + 'Transform'; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration != 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay != 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[TRANSFORM_CAMEL]) { config[TRANSFORM_CAMEL] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; //anim._node.fire('transition:start', data); if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur); return dur + 's'; }, _runNative: function(time) { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { //anim._detach = Y.on(TRANSITION_END, anim._onNativeEnd, node); //node[ON_TRANSITION_END] = anim._onNativeEnd; node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } //setTimeout(function() { // allow updates to apply (size fix, onstart, etc) style.cssText += transitionText + duration + easing + delay + cssText; //}, 1); }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } //node.fire('transition:end', data); } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); } } }, destroy: function() { var anim = this, node = anim._node; /* if (anim._detach) { anim._detach.detach(); } */ //anim._node[ON_TRANSITION_END] = null; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback) { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name == 'boolean') { // no transition, just toggle on = name; name = null; } name = name || Y.Transition.DEFAULT_TOGGLE; if (typeof on == 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).toggleView(name, on, callback); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); Transition.DEFAULT_TOGGLE = 'fade'; }, '@VERSION@' ,{requires:['node-style']}); YUI.add('selector-css2', function(Y) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /** * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, // TODO: move? SORT_RESULTS: true, _children: function(node, tag) { var ret = node.children, i, children = [], childNodes, child; if (node.children && tag && node.children.tags) { children = node.children.tags(tag); } else if ((!ret && node[TAG_NAME]) || (ret && tag)) { // only HTMLElements have children childNodes = ret || node.childNodes; ret = []; for (i = 0; (child = childNodes[i++]);) { if (child.tagName) { if (!tag || tag === child.tagName) { ret.push(child); } } } } return ret || []; }, _re: { attr: /(\[[^\]]*\])/g, esc: /\\[:\[\]\(\)#\.\'\>+~"]/gi, pseudos: /(\([^\)]*\))/g }, /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute //'': '.+', //'=': '^{val}$', // equality '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.Selector._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; // if we have an initial ID, set to root when in document /* if (tokens[0] && rootDoc === root && (id = tokens[0].id) && rootDoc.getElementById(id)) { root = rootDoc.getElementById(id); } */ if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) // TODO: move to allById? if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName('*') child = root.firstChild; while (child) { if (child.tagName) { // only collect HTMLElements nodes.push(child); } child = child.nextSilbing || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, //FUNCTION = 'function', value, tests, test; //do { for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; // use getAttribute for non-standard attributes if (value === undefined && tmpNode.getAttribute) { value = tmpNode.getAttribute(test[0]); } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } }// while (tmpNode = node = nodes[++i]); node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1].toUpperCase(); token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /** Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._replaceShorthand(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceShorthand: function(selector) { var shorthand = Selector.shorthand, esc = selector.match(Selector._re.esc), // pull escaped colon, brackets, etc. attrs, pseudos, re, i, len; if (esc) { selector = selector.replace(Selector._re.esc, '\uE000'); } attrs = selector.match(Selector._re.attr); pseudos = selector.match(Selector._re.pseudos); if (attrs) { selector = selector.replace(Selector._re.attr, '\uE001'); } if (pseudos) { selector = selector.replace(Selector._re.pseudos, '\uE002'); } for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } if (attrs) { for (i = 0, len = attrs.length; i < len; ++i) { selector = selector.replace(/\uE001/, attrs[i]); } } if (pseudos) { for (i = 0, len = pseudos.length; i < len; ++i) { selector = selector.replace(/\uE002/, pseudos[i]); } } selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); if (esc) { for (i = 0, len = esc.length; i < len; ++i) { selector = selector.replace('\uE000', esc[i]); } } return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@' ,{requires:['selector-native']}); YUI.add('selector-css3', function(Y) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.Selector._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.Selector._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.Selector._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.Selector._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.Selector._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.Selector._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@' ,{requires:['selector-native', 'selector-css2']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@' ,{requires:['yui-base']}); YUI.add('dump', function(Y) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@' ); YUI.add('transition-timer', function(Y) { /* * The Transition Utility provides an API for creating advanced transitions. * @module transition */ /* * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@' ,{requires:['transition']}); YUI.add('simpleyui', function(Y) { // empty }, '@VERSION@' ,{use:['yui','oop','dom','event-custom-base','event-base','pluginhost','node','event-delegate','io-base','json-parse','transition','selector-css3','dom-style-ie','querystring-stringify-simple']}); var Y = YUI().use('*');
v0.0.1/app/header.js
reactjs-id/reactjs-id.github.io
import React from 'react'; var styles = { select: { appearance: 'none', '-webkit-appearance': 'none', '-moz-appearance': 'none', width: '100%', padding: '0 20px', border: 'none', color: '#000', borderRadius: 0, background: '#fff' }, image: { background: 'url(img/fb_post.png) no-repeat center center', backgroundSize: 'contain', height: '400px', width: '500px', marginBottom: '30px' } }; class Header extends React.Component { constructor(props) { super(props); this.state = { message: null }; } onSubmit(e) { e.preventDefault(); let email = this.refs.email.value; this.setState({message: null}); axios.post(`https://reactjs-id.herokuapp.com/invite`, { email, channel: 'react-id', coc: 0 }).then(response => { this.setState({message: `Wuut! silakan cek email ${email} :D`}) }, err => { this.setState({message: err.data.msg}) }); } render() { var pendaftar = []; for (var i = 1; i <= 70; i++) { pendaftar.push(i); } let {message} = this.state; return ( <div> <div className="hero-transition-manager"> <section className="hero add show shown"> <div className="center"> <div className="image" style={styles.image}/> <a href="http://live.hacktiv8.com/reactid-march-2017-meetup/" target="_blank" className="btn"> Lihat Event </a> </div> <div className="entrance-transition image-entrance show"><img src="img/logo.png" alt="" className="rimage" /></div> </section> </div> <div className="subscription" id="slack"> <img style={{width: '80px', height: '80px', marginBottom: '10px'}} src="img/slack.png" alt=""/> <h2>React-ID di Slack</h2> <p>Masukkan email Anda untuk mendapatkan undangan dan berdiskusi di Slack.</p> <form onSubmit={this.onSubmit.bind(this)}> <label for="subscription-email" className="label">Masukkan email di sini...</label> <input ref="email" id="slack-email" className="email" placeholder="Enter your email..." required="" /> <button className="submit" type="submit"><span className="submit-text">Dapatkan Undangan</span></button> </form> {message ? <p>{message}</p> : null} </div> </div> ); } }; export default Header;
ajax/libs/react-native-web/0.0.0-4fd133e73/cjs/exports/ProgressBar/index.min.js
cdnjs/cdnjs
"use strict";exports.__esModule=!0,exports.default=void 0;var _StyleSheet=_interopRequireDefault(require("../StyleSheet")),_View=_interopRequireDefault(require("../View")),_react=_interopRequireWildcard(require("react"));function _getRequireWildcardCache(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return _getRequireWildcardCache=function(){return e},e}function _interopRequireWildcard(e){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=_getRequireWildcardCache();if(r&&r.has(e))return r.get(e);var t,n={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&((t=a?Object.getOwnPropertyDescriptor(e,o):null)&&(t.get||t.set)?Object.defineProperty(n,o,t):n[o]=e[o])}return n.default=e,r&&r.set(e,n),n}function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function _extends(){return(_extends=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e}).apply(this,arguments)}function _objectWithoutPropertiesLoose(e,r){if(null==e)return{};for(var t,n={},a=Object.keys(e),o=0;o<a.length;o++)t=a[o],0<=r.indexOf(t)||(n[t]=e[t]);return n}var ProgressBar=(0,_react.forwardRef)(function(e,r){var t=e.color,n=void 0===t?"#1976D2":t,a=e.indeterminate,o=void 0!==a&&a,i=e.progress,s=void 0===i?0:i,l=e.trackColor,u=void 0===l?"transparent":l,c=e.style,f=_objectWithoutPropertiesLoose(e,["color","indeterminate","progress","trackColor","style"]),d=100*s,p=(0,_react.useRef)(null);return(0,_react.useEffect)(function(){var e=o?"25%":d+"%";null!=p.current&&p.current.setNativeProps({style:{width:e}})},[o,d,p]),_react.default.createElement(_View.default,_extends({},f,{accessibilityRole:"progressbar",accessibilityValue:{max:100,min:0,now:o?null:d},ref:r,style:[styles.track,c,{backgroundColor:u}]}),_react.default.createElement(_View.default,{ref:p,style:[styles.progress,o&&styles.animation,{backgroundColor:n}]}))});ProgressBar.displayName="ProgressBar";var styles=_StyleSheet.default.create({track:{height:5,overflow:"hidden",userSelect:"none",zIndex:0},progress:{height:"100%",zIndex:-1},animation:{animationDuration:"1s",animationKeyframes:[{"0%":{transform:[{translateX:"-100%"}]},"100%":{transform:[{translateX:"400%"}]}}],animationTimingFunction:"linear",animationIterationCount:"infinite"}}),_default=ProgressBar;exports.default=ProgressBar,module.exports=exports.default;
ajax/libs/plotly.js/1.39.2/plotly-finance.min.js
jonobr1/cdnjs
/** * plotly.js (finance - minified) v1.39.2 * Copyright 2012-2018, Plotly, Inc. * All rights reserved. * Licensed under the MIT license */ !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Plotly=t()}}(function(){return function(){return function t(e,r,n){function a(o,l){if(!r[o]){if(!e[o]){var s="function"==typeof require&&require;if(!l&&s)return s(o,!0);if(i)return i(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var u=r[o]={exports:{}};e[o][0].call(u.exports,function(t){var r=e[o][1][t];return a(r||t)},u,u.exports,t,e,r,n)}return r[o].exports}for(var i="function"==typeof require&&require,o=0;o<n.length;o++)a(n[o]);return a}}()({1:[function(t,e,r){"use strict";var n=t("../src/lib"),a={"X,X div":"direction:ltr;font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;","X input,X button":"font-family:'Open Sans', verdana, arial, sans-serif;","X input:focus,X button:focus":"outline:none;","X a":"text-decoration:none;","X a:hover":"text-decoration:none;","X .crisp":"shape-rendering:crispEdges;","X .user-select-none":"-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;","X svg":"overflow:hidden;","X svg a":"fill:#447adb;","X svg a:hover":"fill:#3c6dc5;","X .main-svg":"position:absolute;top:0;left:0;pointer-events:none;","X .main-svg .draglayer":"pointer-events:all;","X .cursor-default":"cursor:default;","X .cursor-pointer":"cursor:pointer;","X .cursor-crosshair":"cursor:crosshair;","X .cursor-move":"cursor:move;","X .cursor-col-resize":"cursor:col-resize;","X .cursor-row-resize":"cursor:row-resize;","X .cursor-ns-resize":"cursor:ns-resize;","X .cursor-ew-resize":"cursor:ew-resize;","X .cursor-sw-resize":"cursor:sw-resize;","X .cursor-s-resize":"cursor:s-resize;","X .cursor-se-resize":"cursor:se-resize;","X .cursor-w-resize":"cursor:w-resize;","X .cursor-e-resize":"cursor:e-resize;","X .cursor-nw-resize":"cursor:nw-resize;","X .cursor-n-resize":"cursor:n-resize;","X .cursor-ne-resize":"cursor:ne-resize;","X .cursor-grab":"cursor:-webkit-grab;cursor:grab;","X .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;","X:hover .modebar--hover":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","X [data-title]:before,X [data-title]:after":"position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;","X [data-title]:hover:before,X [data-title]:hover:after":"display:block;opacity:1;","X [data-title]:before":"content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;","X [data-title]:after":"content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;","X .select-outline":"fill:none;stroke-width:1;shape-rendering:crispEdges;","X .select-outline-1":"stroke:white;","X .select-outline-2":"stroke:black;stroke-dasharray:2px 2px;",Y:"font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;","Y p":"margin:0;","Y .notifier-note":"min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;","Y .notifier-close":"color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;","Y .notifier-close:hover":"color:#444;text-decoration:none;cursor:pointer;"};for(var i in a){var o=i.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");n.addStyleRule(o,a[i])}},{"../src/lib":163}],2:[function(t,e,r){"use strict";e.exports={undo:{width:857.1,height:1e3,path:"m857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z",transform:"matrix(1 0 0 -1 0 850)"},home:{width:928.6,height:1e3,path:"m786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z",transform:"matrix(1 0 0 -1 0 850)"},"camera-retro":{width:1e3,height:1e3,path:"m518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z",transform:"matrix(1 0 0 -1 0 850)"},zoombox:{width:1e3,height:1e3,path:"m1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z",transform:"matrix(1 0 0 -1 0 850)"},pan:{width:1e3,height:1e3,path:"m1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z",transform:"matrix(1 0 0 -1 0 850)"},zoom_plus:{width:1e3,height:1e3,path:"m1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z",transform:"matrix(1 0 0 -1 0 850)"},zoom_minus:{width:1e3,height:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",transform:"matrix(1 0 0 -1 0 850)"},autoscale:{width:1e3,height:1e3,path:"m250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z",transform:"matrix(1 0 0 -1 0 850)"},tooltip_basic:{width:1500,height:1e3,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",transform:"matrix(1 0 0 -1 0 850)"},tooltip_compare:{width:1125,height:1e3,path:"m187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z",transform:"matrix(1 0 0 -1 0 850)"},plotlylogo:{width:1542,height:1e3,path:"m0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z",transform:"matrix(1 0 0 -1 0 850)"},"z-axis":{width:1e3,height:1e3,path:"m833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z",transform:"matrix(1 0 0 -1 0 850)"},"3d_rotate":{width:1e3,height:1e3,path:"m922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z",transform:"matrix(1 0 0 -1 0 850)"},camera:{width:1e3,height:1e3,path:"m500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z",transform:"matrix(1 0 0 -1 0 850)"},movie:{width:1e3,height:1e3,path:"m938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z",transform:"matrix(1 0 0 -1 0 850)"},question:{width:857.1,height:1e3,path:"m500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z",transform:"matrix(1 0 0 -1 0 850)"},disk:{width:857.1,height:1e3,path:"m214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z",transform:"matrix(1 0 0 -1 0 850)"},lasso:{width:1031,height:1e3,path:"m1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z",transform:"matrix(1 0 0 -1 0 850)"},selectbox:{width:1e3,height:1e3,path:"m0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z",transform:"matrix(1 0 0 -1 0 850)"},spikeline:{width:1e3,height:1e3,path:"M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z",transform:"matrix(1.5 0 0 -1.5 0 850)"}}},{}],3:[function(t,e,r){"use strict";e.exports=t("../src/traces/bar")},{"../src/traces/bar":261}],4:[function(t,e,r){"use strict";e.exports=t("../src/traces/candlestick")},{"../src/traces/candlestick":279}],5:[function(t,e,r){"use strict";e.exports=t("../src/core")},{"../src/core":148}],6:[function(t,e,r){"use strict";e.exports=t("../src/traces/histogram")},{"../src/traces/histogram":290}],7:[function(t,e,r){"use strict";var n=t("./core");n.register([t("./bar"),t("./histogram"),t("./pie"),t("./ohlc"),t("./candlestick")]),e.exports=n},{"./bar":3,"./candlestick":4,"./core":5,"./histogram":6,"./ohlc":8,"./pie":9}],8:[function(t,e,r){"use strict";e.exports=t("../src/traces/ohlc")},{"../src/traces/ohlc":296}],9:[function(t,e,r){"use strict";e.exports=t("../src/traces/pie")},{"../src/traces/pie":307}],10:[function(t,e,r){!function(){var t={version:"3.5.17"},r=[].slice,n=function(t){return r.call(t)},a=this.document;function i(t){return t&&(t.ownerDocument||t.document||t).documentElement}function o(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}if(a)try{n(a.documentElement.childNodes)[0].nodeType}catch(t){n=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),a)try{a.createElement("DIV").style.setProperty("opacity",0,"")}catch(t){var l=this.Element.prototype,s=l.setAttribute,c=l.setAttributeNS,u=this.CSSStyleDeclaration.prototype,f=u.setProperty;l.setAttribute=function(t,e){s.call(this,t,e+"")},l.setAttributeNS=function(t,e,r){c.call(this,t,e,r+"")},u.setProperty=function(t,e,r){f.call(this,t,e+"",r)}}function d(t,e){return t<e?-1:t>e?1:t>=e?0:NaN}function p(t){return null===t?NaN:+t}function h(t){return!isNaN(t)}function g(t){return{left:function(e,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=e.length);n<a;){var i=n+a>>>1;t(e[i],r)<0?n=i+1:a=i}return n},right:function(e,r,n,a){for(arguments.length<3&&(n=0),arguments.length<4&&(a=e.length);n<a;){var i=n+a>>>1;t(e[i],r)>0?a=i:n=i+1}return n}}}t.ascending=d,t.descending=function(t,e){return e<t?-1:e>t?1:e>=t?0:NaN},t.min=function(t,e){var r,n,a=-1,i=t.length;if(1===arguments.length){for(;++a<i;)if(null!=(n=t[a])&&n>=n){r=n;break}for(;++a<i;)null!=(n=t[a])&&r>n&&(r=n)}else{for(;++a<i;)if(null!=(n=e.call(t,t[a],a))&&n>=n){r=n;break}for(;++a<i;)null!=(n=e.call(t,t[a],a))&&r>n&&(r=n)}return r},t.max=function(t,e){var r,n,a=-1,i=t.length;if(1===arguments.length){for(;++a<i;)if(null!=(n=t[a])&&n>=n){r=n;break}for(;++a<i;)null!=(n=t[a])&&n>r&&(r=n)}else{for(;++a<i;)if(null!=(n=e.call(t,t[a],a))&&n>=n){r=n;break}for(;++a<i;)null!=(n=e.call(t,t[a],a))&&n>r&&(r=n)}return r},t.extent=function(t,e){var r,n,a,i=-1,o=t.length;if(1===arguments.length){for(;++i<o;)if(null!=(n=t[i])&&n>=n){r=a=n;break}for(;++i<o;)null!=(n=t[i])&&(r>n&&(r=n),a<n&&(a=n))}else{for(;++i<o;)if(null!=(n=e.call(t,t[i],i))&&n>=n){r=a=n;break}for(;++i<o;)null!=(n=e.call(t,t[i],i))&&(r>n&&(r=n),a<n&&(a=n))}return[r,a]},t.sum=function(t,e){var r,n=0,a=t.length,i=-1;if(1===arguments.length)for(;++i<a;)h(r=+t[i])&&(n+=r);else for(;++i<a;)h(r=+e.call(t,t[i],i))&&(n+=r);return n},t.mean=function(t,e){var r,n=0,a=t.length,i=-1,o=a;if(1===arguments.length)for(;++i<a;)h(r=p(t[i]))?n+=r:--o;else for(;++i<a;)h(r=p(e.call(t,t[i],i)))?n+=r:--o;if(o)return n/o},t.quantile=function(t,e){var r=(t.length-1)*e+1,n=Math.floor(r),a=+t[n-1],i=r-n;return i?a+i*(t[n]-a):a},t.median=function(e,r){var n,a=[],i=e.length,o=-1;if(1===arguments.length)for(;++o<i;)h(n=p(e[o]))&&a.push(n);else for(;++o<i;)h(n=p(r.call(e,e[o],o)))&&a.push(n);if(a.length)return t.quantile(a.sort(d),.5)},t.variance=function(t,e){var r,n,a=t.length,i=0,o=0,l=-1,s=0;if(1===arguments.length)for(;++l<a;)h(r=p(t[l]))&&(o+=(n=r-i)*(r-(i+=n/++s)));else for(;++l<a;)h(r=p(e.call(t,t[l],l)))&&(o+=(n=r-i)*(r-(i+=n/++s)));if(s>1)return o/(s-1)},t.deviation=function(){var e=t.variance.apply(this,arguments);return e?Math.sqrt(e):e};var y=g(d);function v(t){return t.length}t.bisectLeft=y.left,t.bisect=t.bisectRight=y.right,t.bisector=function(t){return g(1===t.length?function(e,r){return d(t(e),r)}:t)},t.shuffle=function(t,e,r){(i=arguments.length)<3&&(r=t.length,i<2&&(e=0));for(var n,a,i=r-e;i;)a=Math.random()*i--|0,n=t[i+e],t[i+e]=t[a+e],t[a+e]=n;return t},t.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},t.pairs=function(t){for(var e=0,r=t.length-1,n=t[0],a=new Array(r<0?0:r);e<r;)a[e]=[n,n=t[++e]];return a},t.transpose=function(e){if(!(i=e.length))return[];for(var r=-1,n=t.min(e,v),a=new Array(n);++r<n;)for(var i,o=-1,l=a[r]=new Array(i);++o<i;)l[o]=e[o][r];return a},t.zip=function(){return t.transpose(arguments)},t.keys=function(t){var e=[];for(var r in t)e.push(r);return e},t.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},t.entries=function(t){var e=[];for(var r in t)e.push({key:r,value:t[r]});return e},t.merge=function(t){for(var e,r,n,a=t.length,i=-1,o=0;++i<a;)o+=t[i].length;for(r=new Array(o);--a>=0;)for(e=(n=t[a]).length;--e>=0;)r[--o]=n[e];return r};var m=Math.abs;function x(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function b(){this._=Object.create(null)}t.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r==1/0)throw new Error("infinite range");var n,a=[],i=function(t){var e=1;for(;t*e%1;)e*=10;return e}(m(r)),o=-1;if(t*=i,e*=i,(r*=i)<0)for(;(n=t+r*++o)>e;)a.push(n/i);else for(;(n=t+r*++o)<e;)a.push(n/i);return a},t.map=function(t,e){var r=new b;if(t instanceof b)t.forEach(function(t,e){r.set(t,e)});else if(Array.isArray(t)){var n,a=-1,i=t.length;if(1===arguments.length)for(;++a<i;)r.set(a,t[a]);else for(;++a<i;)r.set(e.call(t,n=t[a],a),n)}else for(var o in t)r.set(o,t[o]);return r};var _="__proto__",w="\0";function k(t){return(t+="")===_||t[0]===w?w+t:t}function M(t){return(t+="")[0]===w?t.slice(1):t}function T(t){return k(t)in this._}function A(t){return(t=k(t))in this._&&delete this._[t]}function L(){var t=[];for(var e in this._)t.push(M(e));return t}function C(){var t=0;for(var e in this._)++t;return t}function S(){for(var t in this._)return!1;return!0}function O(){this._=Object.create(null)}function P(t){return t}function D(t,e,r){return function(){var n=r.apply(e,arguments);return n===e?t:n}}function z(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var r=0,n=E.length;r<n;++r){var a=E[r]+e;if(a in t)return a}}x(b,{has:T,get:function(t){return this._[k(t)]},set:function(t,e){return this._[k(t)]=e},remove:A,keys:L,values:function(){var t=[];for(var e in this._)t.push(this._[e]);return t},entries:function(){var t=[];for(var e in this._)t.push({key:M(e),value:this._[e]});return t},size:C,empty:S,forEach:function(t){for(var e in this._)t.call(this,M(e),this._[e])}}),t.nest=function(){var e,r,n={},a=[],i=[];function o(t,i,l){if(l>=a.length)return r?r.call(n,i):e?i.sort(e):i;for(var s,c,u,f,d=-1,p=i.length,h=a[l++],g=new b;++d<p;)(f=g.get(s=h(c=i[d])))?f.push(c):g.set(s,[c]);return t?(c=t(),u=function(e,r){c.set(e,o(t,r,l))}):(c={},u=function(e,r){c[e]=o(t,r,l)}),g.forEach(u),c}return n.map=function(t,e){return o(e,t,0)},n.entries=function(e){return function t(e,r){if(r>=a.length)return e;var n=[],o=i[r++];return e.forEach(function(e,a){n.push({key:e,values:t(a,r)})}),o?n.sort(function(t,e){return o(t.key,e.key)}):n}(o(t.map,e,0),0)},n.key=function(t){return a.push(t),n},n.sortKeys=function(t){return i[a.length-1]=t,n},n.sortValues=function(t){return e=t,n},n.rollup=function(t){return r=t,n},n},t.set=function(t){var e=new O;if(t)for(var r=0,n=t.length;r<n;++r)e.add(t[r]);return e},x(O,{has:T,add:function(t){return this._[k(t+="")]=!0,t},remove:A,values:L,size:C,empty:S,forEach:function(t){for(var e in this._)t.call(this,M(e))}}),t.behavior={},t.rebind=function(t,e){for(var r,n=1,a=arguments.length;++n<a;)t[r=arguments[n]]=D(t,e,e[r]);return t};var E=["webkit","ms","moz","Moz","o","O"];function I(){}function N(){}function R(t){var e=[],r=new b;function n(){for(var r,n=e,a=-1,i=n.length;++a<i;)(r=n[a].on)&&r.apply(this,arguments);return t}return n.on=function(n,a){var i,o=r.get(n);return arguments.length<2?o&&o.on:(o&&(o.on=null,e=e.slice(0,i=e.indexOf(o)).concat(e.slice(i+1)),r.remove(n)),a&&e.push(r.set(n,{on:a})),t)},n}function F(){t.event.preventDefault()}function j(){for(var e,r=t.event;e=r.sourceEvent;)r=e;return r}function B(e){for(var r=new N,n=0,a=arguments.length;++n<a;)r[arguments[n]]=R(r);return r.of=function(n,a){return function(i){try{var o=i.sourceEvent=t.event;i.target=e,t.event=i,r[i.type].apply(n,a)}finally{t.event=o}}},r}t.dispatch=function(){for(var t=new N,e=-1,r=arguments.length;++e<r;)t[arguments[e]]=R(t);return t},N.prototype.on=function(t,e){var r=t.indexOf("."),n="";if(r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},t.event=null,t.requote=function(t){return t.replace(H,"\\$&")};var H=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,q={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]};function V(t){return q(t,X),t}var U=function(t,e){return e.querySelector(t)},G=function(t,e){return e.querySelectorAll(t)},Y=function(t,e){var r=t.matches||t[z(t,"matchesSelector")];return(Y=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(U=function(t,e){return Sizzle(t,e)[0]||null},G=Sizzle,Y=Sizzle.matchesSelector),t.selection=function(){return t.select(a.documentElement)};var X=t.selection.prototype=[];function Z(t){return"function"==typeof t?t:function(){return U(t,this)}}function W(t){return"function"==typeof t?t:function(){return G(t,this)}}X.select=function(t){var e,r,n,a,i=[];t=Z(t);for(var o=-1,l=this.length;++o<l;){i.push(e=[]),e.parentNode=(n=this[o]).parentNode;for(var s=-1,c=n.length;++s<c;)(a=n[s])?(e.push(r=t.call(a,a.__data__,s,o)),r&&"__data__"in a&&(r.__data__=a.__data__)):e.push(null)}return V(i)},X.selectAll=function(t){var e,r,a=[];t=W(t);for(var i=-1,o=this.length;++i<o;)for(var l=this[i],s=-1,c=l.length;++s<c;)(r=l[s])&&(a.push(e=n(t.call(r,r.__data__,s,i))),e.parentNode=r);return V(a)};var Q="http://www.w3.org/1999/xhtml",J={svg:"http://www.w3.org/2000/svg",xhtml:Q,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function $(e,r){return e=t.ns.qualify(e),null==r?e.local?function(){this.removeAttributeNS(e.space,e.local)}:function(){this.removeAttribute(e)}:"function"==typeof r?e.local?function(){var t=r.apply(this,arguments);null==t?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,t)}:function(){var t=r.apply(this,arguments);null==t?this.removeAttribute(e):this.setAttribute(e,t)}:e.local?function(){this.setAttributeNS(e.space,e.local,r)}:function(){this.setAttribute(e,r)}}function K(t){return t.trim().replace(/\s+/g," ")}function tt(e){return new RegExp("(?:^|\\s+)"+t.requote(e)+"(?:\\s+|$)","g")}function et(t){return(t+"").trim().split(/^|\s+/)}function rt(t,e){var r=(t=et(t).map(nt)).length;return"function"==typeof e?function(){for(var n=-1,a=e.apply(this,arguments);++n<r;)t[n](this,a)}:function(){for(var n=-1;++n<r;)t[n](this,e)}}function nt(t){var e=tt(t);return function(r,n){if(a=r.classList)return n?a.add(t):a.remove(t);var a=r.getAttribute("class")||"";n?(e.lastIndex=0,e.test(a)||r.setAttribute("class",K(a+" "+t))):r.setAttribute("class",K(a.replace(e," ")))}}function at(t,e,r){return null==e?function(){this.style.removeProperty(t)}:"function"==typeof e?function(){var n=e.apply(this,arguments);null==n?this.style.removeProperty(t):this.style.setProperty(t,n,r)}:function(){this.style.setProperty(t,e,r)}}function it(t,e){return null==e?function(){delete this[t]}:"function"==typeof e?function(){var r=e.apply(this,arguments);null==r?delete this[t]:this[t]=r}:function(){this[t]=e}}function ot(e){return"function"==typeof e?e:(e=t.ns.qualify(e)).local?function(){return this.ownerDocument.createElementNS(e.space,e.local)}:function(){var t=this.ownerDocument,r=this.namespaceURI;return r===Q&&t.documentElement.namespaceURI===Q?t.createElement(e):t.createElementNS(r,e)}}function lt(){var t=this.parentNode;t&&t.removeChild(this)}function st(t){return{__data__:t}}function ct(t){return function(){return Y(this,t)}}function ut(t,e){for(var r=0,n=t.length;r<n;r++)for(var a,i=t[r],o=0,l=i.length;o<l;o++)(a=i[o])&&e(a,o,r);return t}function ft(t){return q(t,dt),t}t.ns={prefix:J,qualify:function(t){var e=t.indexOf(":"),r=t;return e>=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),J.hasOwnProperty(r)?{space:J[r],local:t}:t}},X.attr=function(e,r){if(arguments.length<2){if("string"==typeof e){var n=this.node();return(e=t.ns.qualify(e)).local?n.getAttributeNS(e.space,e.local):n.getAttribute(e)}for(r in e)this.each($(r,e[r]));return this}return this.each($(e,r))},X.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=et(t)).length,a=-1;if(e=r.classList){for(;++a<n;)if(!e.contains(t[a]))return!1}else for(e=r.getAttribute("class");++a<n;)if(!tt(t[a]).test(e))return!1;return!0}for(e in t)this.each(rt(e,t[e]));return this}return this.each(rt(t,e))},X.style=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=""),t)this.each(at(r,t[r],e));return this}if(n<2){var a=this.node();return o(a).getComputedStyle(a,null).getPropertyValue(t)}r=""}return this.each(at(t,e,r))},X.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(it(e,t[e]));return this}return this.each(it(t,e))},X.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},X.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},X.append=function(t){return t=ot(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},X.insert=function(t,e){return t=ot(t),e=Z(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},X.remove=function(){return this.each(lt)},X.data=function(t,e){var r,n,a=-1,i=this.length;if(!arguments.length){for(t=new Array(i=(r=this[0]).length);++a<i;)(n=r[a])&&(t[a]=n.__data__);return t}function o(t,r){var n,a,i,o=t.length,u=r.length,f=Math.min(o,u),d=new Array(u),p=new Array(u),h=new Array(o);if(e){var g,y=new b,v=new Array(o);for(n=-1;++n<o;)(a=t[n])&&(y.has(g=e.call(a,a.__data__,n))?h[n]=a:y.set(g,a),v[n]=g);for(n=-1;++n<u;)(a=y.get(g=e.call(r,i=r[n],n)))?!0!==a&&(d[n]=a,a.__data__=i):p[n]=st(i),y.set(g,!0);for(n=-1;++n<o;)n in v&&!0!==y.get(v[n])&&(h[n]=t[n])}else{for(n=-1;++n<f;)a=t[n],i=r[n],a?(a.__data__=i,d[n]=a):p[n]=st(i);for(;n<u;++n)p[n]=st(r[n]);for(;n<o;++n)h[n]=t[n]}p.update=d,p.parentNode=d.parentNode=h.parentNode=t.parentNode,l.push(p),s.push(d),c.push(h)}var l=ft([]),s=V([]),c=V([]);if("function"==typeof t)for(;++a<i;)o(r=this[a],t.call(r,r.parentNode.__data__,a));else for(;++a<i;)o(r=this[a],t);return s.enter=function(){return l},s.exit=function(){return c},s},X.datum=function(t){return arguments.length?this.property("__data__",t):this.property("__data__")},X.filter=function(t){var e,r,n,a=[];"function"!=typeof t&&(t=ct(t));for(var i=0,o=this.length;i<o;i++){a.push(e=[]),e.parentNode=(r=this[i]).parentNode;for(var l=0,s=r.length;l<s;l++)(n=r[l])&&t.call(n,n.__data__,l,i)&&e.push(n)}return V(a)},X.order=function(){for(var t=-1,e=this.length;++t<e;)for(var r,n=this[t],a=n.length-1,i=n[a];--a>=0;)(r=n[a])&&(i&&i!==r.nextSibling&&i.parentNode.insertBefore(r,i),i=r);return this},X.sort=function(t){t=function(t){arguments.length||(t=d);return function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}.apply(this,arguments);for(var e=-1,r=this.length;++e<r;)this[e].sort(t);return this.order()},X.each=function(t){return ut(this,function(e,r,n){t.call(e,e.__data__,r,n)})},X.call=function(t){var e=n(arguments);return t.apply(e[0]=this,e),this},X.empty=function(){return!this.node()},X.node=function(){for(var t=0,e=this.length;t<e;t++)for(var r=this[t],n=0,a=r.length;n<a;n++){var i=r[n];if(i)return i}return null},X.size=function(){var t=0;return ut(this,function(){++t}),t};var dt=[];function pt(e,r,a){var i="__on"+e,o=e.indexOf("."),l=gt;o>0&&(e=e.slice(0,o));var s=ht.get(e);function c(){var t=this[i];t&&(this.removeEventListener(e,t,t.$),delete this[i])}return s&&(e=s,l=yt),o?r?function(){var t=l(r,n(arguments));c.call(this),this.addEventListener(e,this[i]=t,t.$=a),t._=r}:c:r?I:function(){var r,n=new RegExp("^__on([^.]+)"+t.requote(e)+"$");for(var a in this)if(r=a.match(n)){var i=this[a];this.removeEventListener(r[1],i,i.$),delete this[a]}}}t.selection.enter=ft,t.selection.enter.prototype=dt,dt.append=X.append,dt.empty=X.empty,dt.node=X.node,dt.call=X.call,dt.size=X.size,dt.select=function(t){for(var e,r,n,a,i,o=[],l=-1,s=this.length;++l<s;){n=(a=this[l]).update,o.push(e=[]),e.parentNode=a.parentNode;for(var c=-1,u=a.length;++c<u;)(i=a[c])?(e.push(n[c]=r=t.call(a.parentNode,i.__data__,c,l)),r.__data__=i.__data__):e.push(null)}return V(o)},dt.insert=function(t,e){var r,n,a;return arguments.length<2&&(r=this,e=function(t,e,i){var o,l=r[i].update,s=l.length;for(i!=a&&(a=i,n=0),e>=n&&(n=e+1);!(o=l[n])&&++n<s;);return o}),X.insert.call(this,t,e)},t.select=function(t){var e;return"string"==typeof t?(e=[U(t,a)]).parentNode=a.documentElement:(e=[t]).parentNode=i(t),V([e])},t.selectAll=function(t){var e;return"string"==typeof t?(e=n(G(t,a))).parentNode=a.documentElement:(e=n(t)).parentNode=null,V([e])},X.on=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=!1),t)this.each(pt(r,t[r],e));return this}if(n<2)return(n=this.node()["__on"+t])&&n._;r=!1}return this.each(pt(t,e,r))};var ht=t.map({mouseenter:"mouseover",mouseleave:"mouseout"});function gt(e,r){return function(n){var a=t.event;t.event=n,r[0]=this.__data__;try{e.apply(this,r)}finally{t.event=a}}}function yt(t,e){var r=gt(t,e);return function(t){var e=t.relatedTarget;e&&(e===this||8&e.compareDocumentPosition(this))||r.call(this,t)}}a&&ht.forEach(function(t){"on"+t in a&&ht.remove(t)});var vt,mt=0;function xt(e){var r=".dragsuppress-"+ ++mt,n="click"+r,a=t.select(o(e)).on("touchmove"+r,F).on("dragstart"+r,F).on("selectstart"+r,F);if(null==vt&&(vt=!("onselectstart"in e)&&z(e.style,"userSelect")),vt){var l=i(e).style,s=l[vt];l[vt]="none"}return function(t){if(a.on(r,null),vt&&(l[vt]=s),t){var e=function(){a.on(n,null)};a.on(n,function(){F(),e()},!0),setTimeout(e,0)}}}t.mouse=function(t){return _t(t,j())};var bt=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;function _t(e,r){r.changedTouches&&(r=r.changedTouches[0]);var n=e.ownerSVGElement||e;if(n.createSVGPoint){var a=n.createSVGPoint();if(bt<0){var i=o(e);if(i.scrollX||i.scrollY){var l=(n=t.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important"))[0][0].getScreenCTM();bt=!(l.f||l.e),n.remove()}}return bt?(a.x=r.pageX,a.y=r.pageY):(a.x=r.clientX,a.y=r.clientY),[(a=a.matrixTransform(e.getScreenCTM().inverse())).x,a.y]}var s=e.getBoundingClientRect();return[r.clientX-s.left-e.clientLeft,r.clientY-s.top-e.clientTop]}function wt(){return t.event.changedTouches[0].identifier}t.touch=function(t,e,r){if(arguments.length<3&&(r=e,e=j().changedTouches),e)for(var n,a=0,i=e.length;a<i;++a)if((n=e[a]).identifier===r)return _t(t,n)},t.behavior.drag=function(){var e=B(i,"drag","dragstart","dragend"),r=null,n=l(I,t.mouse,o,"mousemove","mouseup"),a=l(wt,t.touch,P,"touchmove","touchend");function i(){this.on("mousedown.drag",n).on("touchstart.drag",a)}function l(n,a,i,o,l){return function(){var s,c=t.event.target.correspondingElement||t.event.target,u=this.parentNode,f=e.of(this,arguments),d=0,p=n(),h=".drag"+(null==p?"":"-"+p),g=t.select(i(c)).on(o+h,function(){var t,e,r=a(u,p);if(!r)return;t=r[0]-v[0],e=r[1]-v[1],d|=t|e,v=r,f({type:"drag",x:r[0]+s[0],y:r[1]+s[1],dx:t,dy:e})}).on(l+h,function(){if(!a(u,p))return;g.on(o+h,null).on(l+h,null),y(d),f({type:"dragend"})}),y=xt(c),v=a(u,p);s=r?[(s=r.apply(this,arguments)).x-v[0],s.y-v[1]]:[0,0],f({type:"dragstart"})}}return i.origin=function(t){return arguments.length?(r=t,i):r},t.rebind(i,e,"on")},t.touches=function(t,e){return arguments.length<2&&(e=j().touches),e?n(e).map(function(e){var r=_t(t,e);return r.identifier=e.identifier,r}):[]};var kt=1e-6,Mt=kt*kt,Tt=Math.PI,At=2*Tt,Lt=At-kt,Ct=Tt/2,St=Tt/180,Ot=180/Tt;function Pt(t){return t>0?1:t<0?-1:0}function Dt(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function zt(t){return t>1?0:t<-1?Tt:Math.acos(t)}function Et(t){return t>1?Ct:t<-1?-Ct:Math.asin(t)}function It(t){return((t=Math.exp(t))+1/t)/2}function Nt(t){return(t=Math.sin(t/2))*t}var Rt=Math.SQRT2;t.interpolateZoom=function(t,e){var r,n,a=t[0],i=t[1],o=t[2],l=e[0],s=e[1],c=e[2],u=l-a,f=s-i,d=u*u+f*f;if(d<Mt)n=Math.log(c/o)/Rt,r=function(t){return[a+t*u,i+t*f,o*Math.exp(Rt*t*n)]};else{var p=Math.sqrt(d),h=(c*c-o*o+4*d)/(2*o*2*p),g=(c*c-o*o-4*d)/(2*c*2*p),y=Math.log(Math.sqrt(h*h+1)-h),v=Math.log(Math.sqrt(g*g+1)-g);n=(v-y)/Rt,r=function(t){var e,r=t*n,l=It(y),s=o/(2*p)*(l*(e=Rt*r+y,((e=Math.exp(2*e))-1)/(e+1))-function(t){return((t=Math.exp(t))-1/t)/2}(y));return[a+s*u,i+s*f,o*l/It(Rt*r+y)]}}return r.duration=1e3*n,r},t.behavior.zoom=function(){var e,r,n,i,l,s,c,u,f,d={x:0,y:0,k:1},p=[960,500],h=Bt,g=250,y=0,v="mousedown.zoom",m="mousemove.zoom",x="mouseup.zoom",b="touchstart.zoom",_=B(w,"zoomstart","zoom","zoomend");function w(t){t.on(v,P).on(jt+".zoom",z).on("dblclick.zoom",E).on(b,D)}function k(t){return[(t[0]-d.x)/d.k,(t[1]-d.y)/d.k]}function M(t){d.k=Math.max(h[0],Math.min(h[1],t))}function T(t,e){e=function(t){return[t[0]*d.k+d.x,t[1]*d.k+d.y]}(e),d.x+=t[0]-e[0],d.y+=t[1]-e[1]}function A(e,n,a,i){e.__chart__={x:d.x,y:d.y,k:d.k},M(Math.pow(2,i)),T(r=n,a),e=t.select(e),g>0&&(e=e.transition().duration(g)),e.call(w.event)}function L(){c&&c.domain(s.range().map(function(t){return(t-d.x)/d.k}).map(s.invert)),f&&f.domain(u.range().map(function(t){return(t-d.y)/d.k}).map(u.invert))}function C(t){y++||t({type:"zoomstart"})}function S(t){L(),t({type:"zoom",scale:d.k,translate:[d.x,d.y]})}function O(t){--y||(t({type:"zoomend"}),r=null)}function P(){var e=this,r=_.of(e,arguments),n=0,a=t.select(o(e)).on(m,function(){n=1,T(t.mouse(e),i),S(r)}).on(x,function(){a.on(m,null).on(x,null),l(n),O(r)}),i=k(t.mouse(e)),l=xt(e);fl.call(e),C(r)}function D(){var e,r=this,n=_.of(r,arguments),a={},i=0,o=".zoom-"+t.event.changedTouches[0].identifier,s="touchmove"+o,c="touchend"+o,u=[],f=t.select(r),p=xt(r);function h(){var n=t.touches(r);return e=d.k,n.forEach(function(t){t.identifier in a&&(a[t.identifier]=k(t))}),n}function g(){var e=t.event.target;t.select(e).on(s,y).on(c,m),u.push(e);for(var n=t.event.changedTouches,o=0,f=n.length;o<f;++o)a[n[o].identifier]=null;var p=h(),g=Date.now();if(1===p.length){if(g-l<500){var v=p[0];A(r,v,a[v.identifier],Math.floor(Math.log(d.k)/Math.LN2)+1),F()}l=g}else if(p.length>1){v=p[0];var x=p[1],b=v[0]-x[0],_=v[1]-x[1];i=b*b+_*_}}function y(){var o,s,c,u,f=t.touches(r);fl.call(r);for(var d=0,p=f.length;d<p;++d,u=null)if(c=f[d],u=a[c.identifier]){if(s)break;o=c,s=u}if(u){var h=(h=c[0]-o[0])*h+(h=c[1]-o[1])*h,g=i&&Math.sqrt(h/i);o=[(o[0]+c[0])/2,(o[1]+c[1])/2],s=[(s[0]+u[0])/2,(s[1]+u[1])/2],M(g*e)}l=null,T(o,s),S(n)}function m(){if(t.event.touches.length){for(var e=t.event.changedTouches,r=0,i=e.length;r<i;++r)delete a[e[r].identifier];for(var l in a)return void h()}t.selectAll(u).on(o,null),f.on(v,P).on(b,D),p(),O(n)}g(),C(n),f.on(v,null).on(b,g)}function z(){var a=_.of(this,arguments);i?clearTimeout(i):(fl.call(this),e=k(r=n||t.mouse(this)),C(a)),i=setTimeout(function(){i=null,O(a)},50),F(),M(Math.pow(2,.002*Ft())*d.k),T(r,e),S(a)}function E(){var e=t.mouse(this),r=Math.log(d.k)/Math.LN2;A(this,e,k(e),t.event.shiftKey?Math.ceil(r)-1:Math.floor(r)+1)}return jt||(jt="onwheel"in a?(Ft=function(){return-t.event.deltaY*(t.event.deltaMode?120:1)},"wheel"):"onmousewheel"in a?(Ft=function(){return t.event.wheelDelta},"mousewheel"):(Ft=function(){return-t.event.detail},"MozMousePixelScroll")),w.event=function(e){e.each(function(){var e=_.of(this,arguments),n=d;hl?t.select(this).transition().each("start.zoom",function(){d=this.__chart__||{x:0,y:0,k:1},C(e)}).tween("zoom:zoom",function(){var a=p[0],i=p[1],o=r?r[0]:a/2,l=r?r[1]:i/2,s=t.interpolateZoom([(o-d.x)/d.k,(l-d.y)/d.k,a/d.k],[(o-n.x)/n.k,(l-n.y)/n.k,a/n.k]);return function(t){var r=s(t),n=a/r[2];this.__chart__=d={x:o-r[0]*n,y:l-r[1]*n,k:n},S(e)}}).each("interrupt.zoom",function(){O(e)}).each("end.zoom",function(){O(e)}):(this.__chart__=d,C(e),S(e),O(e))})},w.translate=function(t){return arguments.length?(d={x:+t[0],y:+t[1],k:d.k},L(),w):[d.x,d.y]},w.scale=function(t){return arguments.length?(d={x:d.x,y:d.y,k:null},M(+t),L(),w):d.k},w.scaleExtent=function(t){return arguments.length?(h=null==t?Bt:[+t[0],+t[1]],w):h},w.center=function(t){return arguments.length?(n=t&&[+t[0],+t[1]],w):n},w.size=function(t){return arguments.length?(p=t&&[+t[0],+t[1]],w):p},w.duration=function(t){return arguments.length?(g=+t,w):g},w.x=function(t){return arguments.length?(c=t,s=t.copy(),d={x:0,y:0,k:1},w):c},w.y=function(t){return arguments.length?(f=t,u=t.copy(),d={x:0,y:0,k:1},w):f},t.rebind(w,_,"on")};var Ft,jt,Bt=[0,1/0];function Ht(){}function qt(t,e,r){return this instanceof qt?(this.h=+t,this.s=+e,void(this.l=+r)):arguments.length<2?t instanceof qt?new qt(t.h,t.s,t.l):ue(""+t,fe,qt):new qt(t,e,r)}t.color=Ht,Ht.prototype.toString=function(){return this.rgb()+""},t.hsl=qt;var Vt=qt.prototype=new Ht;function Ut(t,e,r){var n,a;function i(t){return Math.round(255*function(t){return t>360?t-=360:t<0&&(t+=360),t<60?n+(a-n)*t/60:t<180?a:t<240?n+(a-n)*(240-t)/60:n}(t))}return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:e<0?0:e>1?1:e,n=2*(r=r<0?0:r>1?1:r)-(a=r<=.5?r*(1+e):r+e-r*e),new ie(i(t+120),i(t),i(t-120))}function Gt(e,r,n){return this instanceof Gt?(this.h=+e,this.c=+r,void(this.l=+n)):arguments.length<2?e instanceof Gt?new Gt(e.h,e.c,e.l):ee(e instanceof Zt?e.l:(e=de((e=t.rgb(e)).r,e.g,e.b)).l,e.a,e.b):new Gt(e,r,n)}Vt.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new qt(this.h,this.s,this.l/t)},Vt.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new qt(this.h,this.s,t*this.l)},Vt.rgb=function(){return Ut(this.h,this.s,this.l)},t.hcl=Gt;var Yt=Gt.prototype=new Ht;function Xt(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new Zt(r,Math.cos(t*=St)*e,Math.sin(t)*e)}function Zt(t,e,r){return this instanceof Zt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof Zt?new Zt(t.l,t.a,t.b):t instanceof Gt?Xt(t.h,t.c,t.l):de((t=ie(t)).r,t.g,t.b):new Zt(t,e,r)}Yt.brighter=function(t){return new Gt(this.h,this.c,Math.min(100,this.l+Wt*(arguments.length?t:1)))},Yt.darker=function(t){return new Gt(this.h,this.c,Math.max(0,this.l-Wt*(arguments.length?t:1)))},Yt.rgb=function(){return Xt(this.h,this.c,this.l).rgb()},t.lab=Zt;var Wt=18,Qt=.95047,Jt=1,$t=1.08883,Kt=Zt.prototype=new Ht;function te(t,e,r){var n=(t+16)/116,a=n+e/500,i=n-r/200;return new ie(ae(3.2404542*(a=re(a)*Qt)-1.5371385*(n=re(n)*Jt)-.4985314*(i=re(i)*$t)),ae(-.969266*a+1.8760108*n+.041556*i),ae(.0556434*a-.2040259*n+1.0572252*i))}function ee(t,e,r){return t>0?new Gt(Math.atan2(r,e)*Ot,Math.sqrt(e*e+r*r),t):new Gt(NaN,NaN,t)}function re(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function ne(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ae(t){return Math.round(255*(t<=.00304?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ie(t,e,r){return this instanceof ie?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof ie?new ie(t.r,t.g,t.b):ue(""+t,ie,Ut):new ie(t,e,r)}function oe(t){return new ie(t>>16,t>>8&255,255&t)}function le(t){return oe(t)+""}Kt.brighter=function(t){return new Zt(Math.min(100,this.l+Wt*(arguments.length?t:1)),this.a,this.b)},Kt.darker=function(t){return new Zt(Math.max(0,this.l-Wt*(arguments.length?t:1)),this.a,this.b)},Kt.rgb=function(){return te(this.l,this.a,this.b)},t.rgb=ie;var se=ie.prototype=new Ht;function ce(t){return t<16?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function ue(t,e,r){var n,a,i,o=0,l=0,s=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(a=n[2].split(","),n[1]){case"hsl":return r(parseFloat(a[0]),parseFloat(a[1])/100,parseFloat(a[2])/100);case"rgb":return e(he(a[0]),he(a[1]),he(a[2]))}return(i=ge.get(t))?e(i.r,i.g,i.b):(null==t||"#"!==t.charAt(0)||isNaN(i=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&i)>>4,o|=o>>4,l=240&i,l|=l>>4,s=15&i,s|=s<<4):7===t.length&&(o=(16711680&i)>>16,l=(65280&i)>>8,s=255&i)),e(o,l,s))}function fe(t,e,r){var n,a,i=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),l=o-i,s=(o+i)/2;return l?(a=s<.5?l/(o+i):l/(2-o-i),n=t==o?(e-r)/l+(e<r?6:0):e==o?(r-t)/l+2:(t-e)/l+4,n*=60):(n=NaN,a=s>0&&s<1?0:n),new qt(n,a,s)}function de(t,e,r){var n=ne((.4124564*(t=pe(t))+.3575761*(e=pe(e))+.1804375*(r=pe(r)))/Qt),a=ne((.2126729*t+.7151522*e+.072175*r)/Jt);return Zt(116*a-16,500*(n-a),200*(a-ne((.0193339*t+.119192*e+.9503041*r)/$t)))}function pe(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function he(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}se.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,a=30;return e||r||n?(e&&e<a&&(e=a),r&&r<a&&(r=a),n&&n<a&&(n=a),new ie(Math.min(255,e/t),Math.min(255,r/t),Math.min(255,n/t))):new ie(a,a,a)},se.darker=function(t){return new ie((t=Math.pow(.7,arguments.length?t:1))*this.r,t*this.g,t*this.b)},se.hsl=function(){return fe(this.r,this.g,this.b)},se.toString=function(){return"#"+ce(this.r)+ce(this.g)+ce(this.b)};var ge=t.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});function ye(t){return"function"==typeof t?t:function(){return t}}function ve(t){return function(e,r,n){return 2===arguments.length&&"function"==typeof r&&(n=r,r=null),me(e,r,t,n)}}function me(e,r,a,i){var o={},l=t.dispatch("beforesend","progress","load","error"),s={},c=new XMLHttpRequest,u=null;function f(){var t,e=c.status;if(!e&&function(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}(c)||e>=200&&e<300||304===e){try{t=a.call(o,c)}catch(t){return void l.error.call(o,t)}l.load.call(o,t)}else l.error.call(o,c)}return!this.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(e)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=f:c.onreadystatechange=function(){c.readyState>3&&f()},c.onprogress=function(e){var r=t.event;t.event=e;try{l.progress.call(o,c)}finally{t.event=r}},o.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",o)},o.mimeType=function(t){return arguments.length?(r=null==t?null:t+"",o):r},o.responseType=function(t){return arguments.length?(u=t,o):u},o.response=function(t){return a=t,o},["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(n(arguments)))}}),o.send=function(t,n,a){if(2===arguments.length&&"function"==typeof n&&(a=n,n=null),c.open(t,e,!0),null==r||"accept"in s||(s.accept=r+",*/*"),c.setRequestHeader)for(var i in s)c.setRequestHeader(i,s[i]);return null!=r&&c.overrideMimeType&&c.overrideMimeType(r),null!=u&&(c.responseType=u),null!=a&&o.on("error",a).on("load",function(t){a(null,t)}),l.beforesend.call(o,c),c.send(null==n?null:n),o},o.abort=function(){return c.abort(),o},t.rebind(o,l,"on"),null==i?o:o.get(function(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}(i))}ge.forEach(function(t,e){ge.set(t,oe(e))}),t.functor=ye,t.xhr=ve(P),t.dsv=function(t,e){var r=new RegExp('["'+t+"\n]"),n=t.charCodeAt(0);function a(t,r,n){arguments.length<3&&(n=r,r=null);var a=me(t,e,null==r?i:o(r),n);return a.row=function(t){return arguments.length?a.response(null==(r=t)?i:o(t)):r},a}function i(t){return a.parse(t.responseText)}function o(t){return function(e){return a.parse(e.responseText,t)}}function l(e){return e.map(s).join(t)}function s(t){return r.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}return a.parse=function(t,e){var r;return a.parseRows(t,function(t,n){if(r)return r(t,n-1);var a=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,r){return e(a(t),r)}:a})},a.parseRows=function(t,e){var r,a,i={},o={},l=[],s=t.length,c=0,u=0;function f(){if(c>=s)return o;if(a)return a=!1,i;var e=c;if(34===t.charCodeAt(e)){for(var r=e;r++<s;)if(34===t.charCodeAt(r)){if(34!==t.charCodeAt(r+1))break;++r}return c=r+2,13===(l=t.charCodeAt(r+1))?(a=!0,10===t.charCodeAt(r+2)&&++c):10===l&&(a=!0),t.slice(e+1,r).replace(/""/g,'"')}for(;c<s;){var l,u=1;if(10===(l=t.charCodeAt(c++)))a=!0;else if(13===l)a=!0,10===t.charCodeAt(c)&&(++c,++u);else if(l!==n)continue;return t.slice(e,c-u)}return t.slice(e)}for(;(r=f())!==o;){for(var d=[];r!==i&&r!==o;)d.push(r),r=f();e&&null==(d=e(d,u++))||l.push(d)}return l},a.format=function(e){if(Array.isArray(e[0]))return a.formatRows(e);var r=new O,n=[];return e.forEach(function(t){for(var e in t)r.has(e)||n.push(r.add(e))}),[n.map(s).join(t)].concat(e.map(function(e){return n.map(function(t){return s(e[t])}).join(t)})).join("\n")},a.formatRows=function(t){return t.map(l).join("\n")},a},t.csv=t.dsv(",","text/csv"),t.tsv=t.dsv("\t","text/tab-separated-values");var xe,be,_e,we,ke=this[z(this,"requestAnimationFrame")]||function(t){setTimeout(t,17)};function Me(t,e,r){var n=arguments.length;n<2&&(e=0),n<3&&(r=Date.now());var a={c:t,t:r+e,n:null};return be?be.n=a:xe=a,be=a,_e||(we=clearTimeout(we),_e=1,ke(Te)),a}function Te(){var t=Ae(),e=Le()-t;e>24?(isFinite(e)&&(clearTimeout(we),we=setTimeout(Te,e)),_e=0):(_e=1,ke(Te))}function Ae(){for(var t=Date.now(),e=xe;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function Le(){for(var t,e=xe,r=1/0;e;)e.c?(e.t<r&&(r=e.t),e=(t=e).n):e=t?t.n=e.n:xe=e.n;return be=t,r}function Ce(t,e){return e-(t?Math.ceil(Math.log(t)/Math.LN10):1)}t.timer=function(){Me.apply(this,arguments)},t.timer.flush=function(){Ae(),Le()},t.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var Se=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(function(t,e){var r=Math.pow(10,3*m(8-e));return{scale:e>8?function(t){return t/r}:function(t){return t*r},symbol:t}});t.formatPrefix=function(e,r){var n=0;return(e=+e)&&(e<0&&(e*=-1),r&&(e=t.round(e,Ce(e,r))),n=1+Math.floor(1e-12+Math.log(e)/Math.LN10),n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))),Se[8+n/3]};var Oe=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,Pe=t.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(e,r){return(e=t.round(e,Ce(e,r))).toFixed(Math.max(0,Math.min(20,Ce(e*(1+1e-15),r))))}});function De(t){return t+""}var ze=t.time={},Ee=Date;function Ie(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}Ie.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){Ne.setUTCDate.apply(this._,arguments)},setDay:function(){Ne.setUTCDay.apply(this._,arguments)},setFullYear:function(){Ne.setUTCFullYear.apply(this._,arguments)},setHours:function(){Ne.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Ne.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Ne.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Ne.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Ne.setUTCSeconds.apply(this._,arguments)},setTime:function(){Ne.setTime.apply(this._,arguments)}};var Ne=Date.prototype;function Re(t,e,r){function n(e){var r=t(e),n=i(r,1);return e-r<n-e?r:n}function a(r){return e(r=t(new Ee(r-1)),1),r}function i(t,r){return e(t=new Ee(+t),r),t}function o(t,n,i){var o=a(t),l=[];if(i>1)for(;o<n;)r(o)%i||l.push(new Date(+o)),e(o,1);else for(;o<n;)l.push(new Date(+o)),e(o,1);return l}t.floor=t,t.round=n,t.ceil=a,t.offset=i,t.range=o;var l=t.utc=Fe(t);return l.floor=l,l.round=Fe(n),l.ceil=Fe(a),l.offset=Fe(i),l.range=function(t,e,r){try{Ee=Ie;var n=new Ie;return n._=t,o(n,e,r)}finally{Ee=Date}},t}function Fe(t){return function(e,r){try{Ee=Ie;var n=new Ie;return n._=e,t(n,r)._}finally{Ee=Date}}}ze.year=Re(function(t){return(t=ze.day(t)).setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),ze.years=ze.year.range,ze.years.utc=ze.year.utc.range,ze.day=Re(function(t){var e=new Ee(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),ze.days=ze.day.range,ze.days.utc=ze.day.utc.range,ze.dayOfYear=function(t){var e=ze.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var r=ze[t]=Re(function(t){return(t=ze.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var r=ze.year(t).getDay();return Math.floor((ze.dayOfYear(t)+(r+e)%7)/7)-(r!==e)});ze[t+"s"]=r.range,ze[t+"s"].utc=r.utc.range,ze[t+"OfYear"]=function(t){var r=ze.year(t).getDay();return Math.floor((ze.dayOfYear(t)+(r+e)%7)/7)}}),ze.week=ze.sunday,ze.weeks=ze.sunday.range,ze.weeks.utc=ze.sunday.utc.range,ze.weekOfYear=ze.sundayOfYear;var je={"-":"",_:" ",0:"0"},Be=/^\s*\d+/,He=/^%/;function qe(t,e,r){var n=t<0?"-":"",a=(n?-t:t)+"",i=a.length;return n+(i<r?new Array(r-i+1).join(e)+a:a)}function Ve(e){return new RegExp("^(?:"+e.map(t.requote).join("|")+")","i")}function Ue(t){for(var e=new b,r=-1,n=t.length;++r<n;)e.set(t[r].toLowerCase(),r);return e}function Ge(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function Ye(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r));return n?(t.U=+n[0],r+n[0].length):-1}function Xe(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r));return n?(t.W=+n[0],r+n[0].length):-1}function Ze(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function We(t,e,r){Be.lastIndex=0;var n,a=Be.exec(e.slice(r,r+2));return a?(t.y=(n=+a[0])+(n>68?1900:2e3),r+a[0].length):-1}function Qe(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function Je(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function $e(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function Ke(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function tr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function er(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function rr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function nr(t,e,r){Be.lastIndex=0;var n=Be.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function ar(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=m(e)/60|0,a=m(e)%60;return r+qe(n,"0",2)+qe(a,"0",2)}function ir(t,e,r){He.lastIndex=0;var n=He.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function or(t){for(var e=t.length,r=-1;++r<e;)t[r][0]=this(t[r][0]);return function(e){for(var r=0,n=t[r];!n[1](e);)n=t[++r];return n[0](e)}}t.locale=function(e){return{numberFormat:function(e){var r=e.decimal,n=e.thousands,a=e.grouping,i=e.currency,o=a&&n?function(t,e){for(var r=t.length,i=[],o=0,l=a[0],s=0;r>0&&l>0&&(s+l+1>e&&(l=Math.max(1,e-s)),i.push(t.substring(r-=l,r+l)),!((s+=l+1)>e));)l=a[o=(o+1)%a.length];return i.reverse().join(n)}:P;return function(e){var n=Oe.exec(e),a=n[1]||" ",l=n[2]||">",s=n[3]||"-",c=n[4]||"",u=n[5],f=+n[6],d=n[7],p=n[8],h=n[9],g=1,y="",v="",m=!1,x=!0;switch(p&&(p=+p.substring(1)),(u||"0"===a&&"="===l)&&(u=a="0",l="="),h){case"n":d=!0,h="g";break;case"%":g=100,v="%",h="f";break;case"p":g=100,v="%",h="r";break;case"b":case"o":case"x":case"X":"#"===c&&(y="0"+h.toLowerCase());case"c":x=!1;case"d":m=!0,p=0;break;case"s":g=-1,h="r"}"$"===c&&(y=i[0],v=i[1]),"r"!=h||p||(h="g"),null!=p&&("g"==h?p=Math.max(1,Math.min(21,p)):"e"!=h&&"f"!=h||(p=Math.max(0,Math.min(20,p)))),h=Pe.get(h)||De;var b=u&&d;return function(e){var n=v;if(m&&e%1)return"";var i=e<0||0===e&&1/e<0?(e=-e,"-"):"-"===s?"":s;if(g<0){var c=t.formatPrefix(e,p);e=c.scale(e),n=c.symbol+v}else e*=g;var _,w,k=(e=h(e,p)).lastIndexOf(".");if(k<0){var M=x?e.lastIndexOf("e"):-1;M<0?(_=e,w=""):(_=e.substring(0,M),w=e.substring(M))}else _=e.substring(0,k),w=r+e.substring(k+1);!u&&d&&(_=o(_,1/0));var T=y.length+_.length+w.length+(b?0:i.length),A=T<f?new Array(T=f-T+1).join(a):"";return b&&(_=o(A+_,A.length?f-w.length:1/0)),i+=y,e=_+w,("<"===l?i+e+A:">"===l?A+i+e:"^"===l?A.substring(0,T>>=1)+i+e+A.substring(T):i+(b?e:A+e))+n}}}(e),timeFormat:function(e){var r=e.dateTime,n=e.date,a=e.time,i=e.periods,o=e.days,l=e.shortDays,s=e.months,c=e.shortMonths;function u(t){var e=t.length;function r(r){for(var n,a,i,o=[],l=-1,s=0;++l<e;)37===t.charCodeAt(l)&&(o.push(t.slice(s,l)),null!=(a=je[n=t.charAt(++l)])&&(n=t.charAt(++l)),(i=_[n])&&(n=i(r,null==a?"e"===n?" ":"0":a)),o.push(n),s=l+1);return o.push(t.slice(s,l)),o.join("")}return r.parse=function(e){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null};if(f(r,t,e,0)!=e.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var n=null!=r.Z&&Ee!==Ie,a=new(n?Ie:Ee);return"j"in r?a.setFullYear(r.y,0,r.j):"W"in r||"U"in r?("w"in r||(r.w="W"in r?1:0),a.setFullYear(r.y,0,1),a.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(a.getDay()+5)%7:r.w+7*r.U-(a.getDay()+6)%7)):a.setFullYear(r.y,r.m,r.d),a.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L),n?a._:a},r.toString=function(){return t},r}function f(t,e,r,n){for(var a,i,o,l=0,s=e.length,c=r.length;l<s;){if(n>=c)return-1;if(37===(a=e.charCodeAt(l++))){if(o=e.charAt(l++),!(i=w[o in je?e.charAt(l++):o])||(n=i(t,r,n))<0)return-1}else if(a!=r.charCodeAt(n++))return-1}return n}u.utc=function(t){var e=u(t);function r(t){try{var r=new(Ee=Ie);return r._=t,e(r)}finally{Ee=Date}}return r.parse=function(t){try{Ee=Ie;var r=e.parse(t);return r&&r._}finally{Ee=Date}},r.toString=e.toString,r},u.multi=u.utc.multi=or;var d=t.map(),p=Ve(o),h=Ue(o),g=Ve(l),y=Ue(l),v=Ve(s),m=Ue(s),x=Ve(c),b=Ue(c);i.forEach(function(t,e){d.set(t.toLowerCase(),e)});var _={a:function(t){return l[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return s[t.getMonth()]},c:u(r),d:function(t,e){return qe(t.getDate(),e,2)},e:function(t,e){return qe(t.getDate(),e,2)},H:function(t,e){return qe(t.getHours(),e,2)},I:function(t,e){return qe(t.getHours()%12||12,e,2)},j:function(t,e){return qe(1+ze.dayOfYear(t),e,3)},L:function(t,e){return qe(t.getMilliseconds(),e,3)},m:function(t,e){return qe(t.getMonth()+1,e,2)},M:function(t,e){return qe(t.getMinutes(),e,2)},p:function(t){return i[+(t.getHours()>=12)]},S:function(t,e){return qe(t.getSeconds(),e,2)},U:function(t,e){return qe(ze.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return qe(ze.mondayOfYear(t),e,2)},x:u(n),X:u(a),y:function(t,e){return qe(t.getFullYear()%100,e,2)},Y:function(t,e){return qe(t.getFullYear()%1e4,e,4)},Z:ar,"%":function(){return"%"}},w={a:function(t,e,r){g.lastIndex=0;var n=g.exec(e.slice(r));return n?(t.w=y.get(n[0].toLowerCase()),r+n[0].length):-1},A:function(t,e,r){p.lastIndex=0;var n=p.exec(e.slice(r));return n?(t.w=h.get(n[0].toLowerCase()),r+n[0].length):-1},b:function(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.m=b.get(n[0].toLowerCase()),r+n[0].length):-1},B:function(t,e,r){v.lastIndex=0;var n=v.exec(e.slice(r));return n?(t.m=m.get(n[0].toLowerCase()),r+n[0].length):-1},c:function(t,e,r){return f(t,_.c.toString(),e,r)},d:$e,e:$e,H:tr,I:tr,j:Ke,L:nr,m:Je,M:er,p:function(t,e,r){var n=d.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)},S:rr,U:Ye,w:Ge,W:Xe,x:function(t,e,r){return f(t,_.x.toString(),e,r)},X:function(t,e,r){return f(t,_.X.toString(),e,r)},y:We,Y:Ze,Z:Qe,"%":ir};return u}(e)}};var lr=t.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],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"]});function sr(){}t.format=lr.numberFormat,t.geo={},sr.prototype={s:0,t:0,add:function(t){ur(t,this.t,cr),ur(cr.s,this.s,this),this.s?this.t+=cr.t:this.s=cr.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cr=new sr;function ur(t,e,r){var n=r.s=t+e,a=n-t,i=n-a;r.t=t-i+(e-a)}function fr(t,e){t&&pr.hasOwnProperty(t.type)&&pr[t.type](t,e)}t.geo.stream=function(t,e){t&&dr.hasOwnProperty(t.type)?dr[t.type](t,e):fr(t,e)};var dr={Feature:function(t,e){fr(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,a=r.length;++n<a;)fr(r[n].geometry,e)}},pr={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var r=t.coordinates,n=-1,a=r.length;++n<a;)t=r[n],e.point(t[0],t[1],t[2])},LineString:function(t,e){hr(t.coordinates,e,0)},MultiLineString:function(t,e){for(var r=t.coordinates,n=-1,a=r.length;++n<a;)hr(r[n],e,0)},Polygon:function(t,e){gr(t.coordinates,e)},MultiPolygon:function(t,e){for(var r=t.coordinates,n=-1,a=r.length;++n<a;)gr(r[n],e)},GeometryCollection:function(t,e){for(var r=t.geometries,n=-1,a=r.length;++n<a;)fr(r[n],e)}};function hr(t,e,r){var n,a=-1,i=t.length-r;for(e.lineStart();++a<i;)n=t[a],e.point(n[0],n[1],n[2]);e.lineEnd()}function gr(t,e){var r=-1,n=t.length;for(e.polygonStart();++r<n;)hr(t[r],e,1);e.polygonEnd()}t.geo.area=function(e){return yr=0,t.geo.stream(e,Sr),yr};var yr,vr,mr,xr,br,_r,wr,kr,Mr,Tr,Ar,Lr,Cr=new sr,Sr={sphere:function(){yr+=4*Tt},point:I,lineStart:I,lineEnd:I,polygonStart:function(){Cr.reset(),Sr.lineStart=Or},polygonEnd:function(){var t=2*Cr;yr+=t<0?4*Tt+t:t,Sr.lineStart=Sr.lineEnd=Sr.point=I}};function Or(){var t,e,r,n,a;function i(t,e){e=e*St/2+Tt/4;var i=(t*=St)-r,o=i>=0?1:-1,l=o*i,s=Math.cos(e),c=Math.sin(e),u=a*c,f=n*s+u*Math.cos(l),d=u*o*Math.sin(l);Cr.add(Math.atan2(d,f)),r=t,n=s,a=c}Sr.point=function(o,l){Sr.point=i,r=(t=o)*St,n=Math.cos(l=(e=l)*St/2+Tt/4),a=Math.sin(l)},Sr.lineEnd=function(){i(t,e)}}function Pr(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function Dr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function zr(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function Er(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function Ir(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Nr(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Rr(t){return[Math.atan2(t[1],t[0]),Et(t[2])]}function Fr(t,e){return m(t[0]-e[0])<kt&&m(t[1]-e[1])<kt}t.geo.bounds=function(){var e,r,n,a,i,o,l,s,c,u,f,d={point:p,lineStart:g,lineEnd:y,polygonStart:function(){d.point=v,d.lineStart=x,d.lineEnd=b,c=0,Sr.polygonStart()},polygonEnd:function(){Sr.polygonEnd(),d.point=p,d.lineStart=g,d.lineEnd=y,Cr<0?(e=-(n=180),r=-(a=90)):c>kt?a=90:c<-kt&&(r=-90),f[0]=e,f[1]=n}};function p(t,i){u.push(f=[e=t,n=t]),i<r&&(r=i),i>a&&(a=i)}function h(t,o){var l=Pr([t*St,o*St]);if(s){var c=zr(s,l),u=zr([c[1],-c[0],0],c);Nr(u),u=Rr(u);var f=t-i,d=f>0?1:-1,h=u[0]*Ot*d,g=m(f)>180;if(g^(d*i<h&&h<d*t))(y=u[1]*Ot)>a&&(a=y);else if(g^(d*i<(h=(h+360)%360-180)&&h<d*t)){var y;(y=-u[1]*Ot)<r&&(r=y)}else o<r&&(r=o),o>a&&(a=o);g?t<i?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t):n>=e?(t<e&&(e=t),t>n&&(n=t)):t>i?_(e,t)>_(e,n)&&(n=t):_(t,n)>_(e,n)&&(e=t)}else p(t,o);s=l,i=t}function g(){d.point=h}function y(){f[0]=e,f[1]=n,d.point=p,s=null}function v(t,e){if(s){var r=t-i;c+=m(r)>180?r+(r>0?360:-360):r}else o=t,l=e;Sr.point(t,e),h(t,e)}function x(){Sr.lineStart()}function b(){v(o,l),Sr.lineEnd(),m(c)>kt&&(e=-(n=180)),f[0]=e,f[1]=n,s=null}function _(t,e){return(e-=t)<0?e+360:e}function w(t,e){return t[0]-e[0]}function k(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t<e[0]||e[1]<t}return function(i){if(a=n=-(e=r=1/0),u=[],t.geo.stream(i,d),c=u.length){u.sort(w);for(var o=1,l=[g=u[0]];o<c;++o)k((p=u[o])[0],g)||k(p[1],g)?(_(g[0],p[1])>_(g[0],g[1])&&(g[1]=p[1]),_(p[0],g[1])>_(g[0],g[1])&&(g[0]=p[0])):l.push(g=p);for(var s,c,p,h=-1/0,g=(o=0,l[c=l.length-1]);o<=c;g=p,++o)p=l[o],(s=_(g[1],p[0]))>h&&(h=s,e=p[0],n=g[1])}return u=f=null,e===1/0||r===1/0?[[NaN,NaN],[NaN,NaN]]:[[e,r],[n,a]]}}(),t.geo.centroid=function(e){vr=mr=xr=br=_r=wr=kr=Mr=Tr=Ar=Lr=0,t.geo.stream(e,jr);var r=Tr,n=Ar,a=Lr,i=r*r+n*n+a*a;return i<Mt&&(r=wr,n=kr,a=Mr,mr<kt&&(r=xr,n=br,a=_r),(i=r*r+n*n+a*a)<Mt)?[NaN,NaN]:[Math.atan2(n,r)*Ot,Et(a/Math.sqrt(i))*Ot]};var jr={sphere:I,point:Br,lineStart:qr,lineEnd:Vr,polygonStart:function(){jr.lineStart=Ur},polygonEnd:function(){jr.lineStart=qr}};function Br(t,e){t*=St;var r=Math.cos(e*=St);Hr(r*Math.cos(t),r*Math.sin(t),Math.sin(e))}function Hr(t,e,r){xr+=(t-xr)/++vr,br+=(e-br)/vr,_r+=(r-_r)/vr}function qr(){var t,e,r;function n(n,a){n*=St;var i=Math.cos(a*=St),o=i*Math.cos(n),l=i*Math.sin(n),s=Math.sin(a),c=Math.atan2(Math.sqrt((c=e*s-r*l)*c+(c=r*o-t*s)*c+(c=t*l-e*o)*c),t*o+e*l+r*s);mr+=c,wr+=c*(t+(t=o)),kr+=c*(e+(e=l)),Mr+=c*(r+(r=s)),Hr(t,e,r)}jr.point=function(a,i){a*=St;var o=Math.cos(i*=St);t=o*Math.cos(a),e=o*Math.sin(a),r=Math.sin(i),jr.point=n,Hr(t,e,r)}}function Vr(){jr.point=Br}function Ur(){var t,e,r,n,a;function i(t,e){t*=St;var i=Math.cos(e*=St),o=i*Math.cos(t),l=i*Math.sin(t),s=Math.sin(e),c=n*s-a*l,u=a*o-r*s,f=r*l-n*o,d=Math.sqrt(c*c+u*u+f*f),p=r*o+n*l+a*s,h=d&&-zt(p)/d,g=Math.atan2(d,p);Tr+=h*c,Ar+=h*u,Lr+=h*f,mr+=g,wr+=g*(r+(r=o)),kr+=g*(n+(n=l)),Mr+=g*(a+(a=s)),Hr(r,n,a)}jr.point=function(o,l){t=o,e=l,jr.point=i,o*=St;var s=Math.cos(l*=St);r=s*Math.cos(o),n=s*Math.sin(o),a=Math.sin(l),Hr(r,n,a)},jr.lineEnd=function(){i(t,e),jr.lineEnd=Vr,jr.point=Br}}function Gr(t,e){function r(r,n){return r=t(r,n),e(r[0],r[1])}return t.invert&&e.invert&&(r.invert=function(r,n){return(r=e.invert(r,n))&&t.invert(r[0],r[1])}),r}function Yr(){return!0}function Xr(t,e,r,n,a){var i=[],o=[];if(t.forEach(function(t){if(!((e=t.length-1)<=0)){var e,r=t[0],n=t[e];if(Fr(r,n)){a.lineStart();for(var l=0;l<e;++l)a.point((r=t[l])[0],r[1]);a.lineEnd()}else{var s=new Wr(r,t,null,!0),c=new Wr(r,null,s,!1);s.o=c,i.push(s),o.push(c),s=new Wr(n,t,null,!1),c=new Wr(n,null,s,!0),s.o=c,i.push(s),o.push(c)}}}),o.sort(e),Zr(i),Zr(o),i.length){for(var l=0,s=r,c=o.length;l<c;++l)o[l].e=s=!s;for(var u,f,d=i[0];;){for(var p=d,h=!0;p.v;)if((p=p.n)===d)return;u=p.z,a.lineStart();do{if(p.v=p.o.v=!0,p.e){if(h)for(l=0,c=u.length;l<c;++l)a.point((f=u[l])[0],f[1]);else n(p.x,p.n.x,1,a);p=p.n}else{if(h)for(l=(u=p.p.z).length-1;l>=0;--l)a.point((f=u[l])[0],f[1]);else n(p.x,p.p.x,-1,a);p=p.p}u=(p=p.o).z,h=!h}while(!p.v);a.lineEnd()}}}function Zr(t){if(e=t.length){for(var e,r,n=0,a=t[0];++n<e;)a.n=r=t[n],r.p=a,a=r;a.n=r=t[0],r.p=a}}function Wr(t,e,r,n){this.x=t,this.z=e,this.o=r,this.e=n,this.v=!1,this.n=this.p=null}function Qr(e,r,n,a){return function(i,o){var l,s=r(o),c=i.invert(a[0],a[1]),u={point:f,lineStart:p,lineEnd:h,polygonStart:function(){u.point=b,u.lineStart=_,u.lineEnd=w,l=[],g=[]},polygonEnd:function(){u.point=f,u.lineStart=p,u.lineEnd=h,l=t.merge(l);var e=function(t,e){var r=t[0],n=t[1],a=[Math.sin(r),-Math.cos(r),0],i=0,o=0;Cr.reset();for(var l=0,s=e.length;l<s;++l){var c=e[l],u=c.length;if(u)for(var f=c[0],d=f[0],p=f[1]/2+Tt/4,h=Math.sin(p),g=Math.cos(p),y=1;;){y===u&&(y=0);var v=(t=c[y])[0],m=t[1]/2+Tt/4,x=Math.sin(m),b=Math.cos(m),_=v-d,w=_>=0?1:-1,k=w*_,M=k>Tt,T=h*x;if(Cr.add(Math.atan2(T*w*Math.sin(k),g*b+T*Math.cos(k))),i+=M?_+w*At:_,M^d>=r^v>=r){var A=zr(Pr(f),Pr(t));Nr(A);var L=zr(a,A);Nr(L);var C=(M^_>=0?-1:1)*Et(L[2]);(n>C||n===C&&(A[0]||A[1]))&&(o+=M^_>=0?1:-1)}if(!y++)break;d=v,h=x,g=b,f=t}}return(i<-kt||i<kt&&Cr<-kt)^1&o}(c,g);l.length?(x||(o.polygonStart(),x=!0),Xr(l,Kr,e,n,o)):e&&(x||(o.polygonStart(),x=!0),o.lineStart(),n(null,null,1,o),o.lineEnd()),x&&(o.polygonEnd(),x=!1),l=g=null},sphere:function(){o.polygonStart(),o.lineStart(),n(null,null,1,o),o.lineEnd(),o.polygonEnd()}};function f(t,r){var n=i(t,r);e(t=n[0],r=n[1])&&o.point(t,r)}function d(t,e){var r=i(t,e);s.point(r[0],r[1])}function p(){u.point=d,s.lineStart()}function h(){u.point=f,s.lineEnd()}var g,y,v=$r(),m=r(v),x=!1;function b(t,e){y.push([t,e]);var r=i(t,e);m.point(r[0],r[1])}function _(){m.lineStart(),y=[]}function w(){b(y[0][0],y[0][1]),m.lineEnd();var t,e=m.clean(),r=v.buffer(),n=r.length;if(y.pop(),g.push(y),y=null,n)if(1&e){var a,i=-1;if((n=(t=r[0]).length-1)>0){for(x||(o.polygonStart(),x=!0),o.lineStart();++i<n;)o.point((a=t[i])[0],a[1]);o.lineEnd()}}else n>1&&2&e&&r.push(r.pop().concat(r.shift())),l.push(r.filter(Jr))}return u}}function Jr(t){return t.length>1}function $r(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:I,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Kr(t,e){return((t=t.x)[0]<0?t[1]-Ct-kt:Ct-t[1])-((e=e.x)[0]<0?e[1]-Ct-kt:Ct-e[1])}var tn=Qr(Yr,function(t){var e,r=NaN,n=NaN,a=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(i,o){var l=i>0?Tt:-Tt,s=m(i-r);m(s-Tt)<kt?(t.point(r,n=(n+o)/2>0?Ct:-Ct),t.point(a,n),t.lineEnd(),t.lineStart(),t.point(l,n),t.point(i,n),e=0):a!==l&&s>=Tt&&(m(r-a)<kt&&(r-=a*kt),m(i-l)<kt&&(i-=l*kt),n=function(t,e,r,n){var a,i,o=Math.sin(t-r);return m(o)>kt?Math.atan((Math.sin(e)*(i=Math.cos(n))*Math.sin(r)-Math.sin(n)*(a=Math.cos(e))*Math.sin(t))/(a*i*o)):(e+n)/2}(r,n,i,o),t.point(a,n),t.lineEnd(),t.lineStart(),t.point(l,n),e=0),t.point(r=i,n=o),a=l},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}},function(t,e,r,n){var a;if(null==t)a=r*Ct,n.point(-Tt,a),n.point(0,a),n.point(Tt,a),n.point(Tt,0),n.point(Tt,-a),n.point(0,-a),n.point(-Tt,-a),n.point(-Tt,0),n.point(-Tt,a);else if(m(t[0]-e[0])>kt){var i=t[0]<e[0]?Tt:-Tt;a=r*i/2,n.point(-i,a),n.point(0,a),n.point(i,a)}else n.point(e[0],e[1])},[-Tt,-Tt/2]);function en(t,e,r,n){return function(a){var i,o=a.a,l=a.b,s=o.x,c=o.y,u=0,f=1,d=l.x-s,p=l.y-c;if(i=t-s,d||!(i>0)){if(i/=d,d<0){if(i<u)return;i<f&&(f=i)}else if(d>0){if(i>f)return;i>u&&(u=i)}if(i=r-s,d||!(i<0)){if(i/=d,d<0){if(i>f)return;i>u&&(u=i)}else if(d>0){if(i<u)return;i<f&&(f=i)}if(i=e-c,p||!(i>0)){if(i/=p,p<0){if(i<u)return;i<f&&(f=i)}else if(p>0){if(i>f)return;i>u&&(u=i)}if(i=n-c,p||!(i<0)){if(i/=p,p<0){if(i>f)return;i>u&&(u=i)}else if(p>0){if(i<u)return;i<f&&(f=i)}return u>0&&(a.a={x:s+u*d,y:c+u*p}),f<1&&(a.b={x:s+f*d,y:c+f*p}),a}}}}}}var rn=1e9;function nn(e,r,n,a){return function(s){var c,u,f,d,p,h,g,y,v,m,x,b=s,_=$r(),w=en(e,r,n,a),k={point:A,lineStart:function(){k.point=L,u&&u.push(f=[]);m=!0,v=!1,g=y=NaN},lineEnd:function(){c&&(L(d,p),h&&v&&_.rejoin(),c.push(_.buffer()));k.point=A,v&&s.lineEnd()},polygonStart:function(){s=_,c=[],u=[],x=!0},polygonEnd:function(){s=b,c=t.merge(c);var r=function(t){for(var e=0,r=u.length,n=t[1],a=0;a<r;++a)for(var i,o=1,l=u[a],s=l.length,c=l[0];o<s;++o)i=l[o],c[1]<=n?i[1]>n&&Dt(c,i,t)>0&&++e:i[1]<=n&&Dt(c,i,t)<0&&--e,c=i;return 0!==e}([e,a]),n=x&&r,i=c.length;(n||i)&&(s.polygonStart(),n&&(s.lineStart(),M(null,null,1,s),s.lineEnd()),i&&Xr(c,o,r,M,s),s.polygonEnd()),c=u=f=null}};function M(t,o,s,c){var u=0,f=0;if(null==t||(u=i(t,s))!==(f=i(o,s))||l(t,o)<0^s>0)do{c.point(0===u||3===u?e:n,u>1?a:r)}while((u=(u+s+4)%4)!==f);else c.point(o[0],o[1])}function T(t,i){return e<=t&&t<=n&&r<=i&&i<=a}function A(t,e){T(t,e)&&s.point(t,e)}function L(t,e){var r=T(t=Math.max(-rn,Math.min(rn,t)),e=Math.max(-rn,Math.min(rn,e)));if(u&&f.push([t,e]),m)d=t,p=e,h=r,m=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&v)s.point(t,e);else{var n={a:{x:g,y:y},b:{x:t,y:e}};w(n)?(v||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),x=!1):r&&(s.lineStart(),s.point(t,e),x=!1)}g=t,y=e,v=r}return k};function i(t,a){return m(t[0]-e)<kt?a>0?0:3:m(t[0]-n)<kt?a>0?2:1:m(t[1]-r)<kt?a>0?1:0:a>0?3:2}function o(t,e){return l(t.x,e.x)}function l(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}}function an(t){var e=0,r=Tt/3,n=Sn(t),a=n(e,r);return a.parallels=function(t){return arguments.length?n(e=t[0]*Tt/180,r=t[1]*Tt/180):[e/Tt*180,r/Tt*180]},a}function on(t,e){var r=Math.sin(t),n=(r+Math.sin(e))/2,a=1+r*(2*n-r),i=Math.sqrt(a)/n;function o(t,e){var r=Math.sqrt(a-2*n*Math.sin(e))/n;return[r*Math.sin(t*=n),i-r*Math.cos(t)]}return o.invert=function(t,e){var r=i-e;return[Math.atan2(t,r)/n,Et((a-(t*t+r*r)*n*n)/(2*n))]},o}t.geo.clipExtent=function(){var t,e,r,n,a,i,o={stream:function(t){return a&&(a.valid=!1),(a=i(t)).valid=!0,a},extent:function(l){return arguments.length?(i=nn(t=+l[0][0],e=+l[0][1],r=+l[1][0],n=+l[1][1]),a&&(a.valid=!1,a=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(t.geo.conicEqualArea=function(){return an(on)}).raw=on,t.geo.albers=function(){return t.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},t.geo.albersUsa=function(){var e,r,n,a,i=t.geo.albers(),o=t.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),l=t.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),s={point:function(t,r){e=[t,r]}};function c(t){var i=t[0],o=t[1];return e=null,r(i,o),e||(n(i,o),e)||a(i,o),e}return c.invert=function(t){var e=i.scale(),r=i.translate(),n=(t[0]-r[0])/e,a=(t[1]-r[1])/e;return(a>=.12&&a<.234&&n>=-.425&&n<-.214?o:a>=.166&&a<.234&&n>=-.214&&n<-.115?l:i).invert(t)},c.stream=function(t){var e=i.stream(t),r=o.stream(t),n=l.stream(t);return{point:function(t,a){e.point(t,a),r.point(t,a),n.point(t,a)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},c.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),l.precision(t),c):i.precision()},c.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),l.scale(t),c.translate(i.translate())):i.scale()},c.translate=function(t){if(!arguments.length)return i.translate();var e=i.scale(),u=+t[0],f=+t[1];return r=i.translate(t).clipExtent([[u-.455*e,f-.238*e],[u+.455*e,f+.238*e]]).stream(s).point,n=o.translate([u-.307*e,f+.201*e]).clipExtent([[u-.425*e+kt,f+.12*e+kt],[u-.214*e-kt,f+.234*e-kt]]).stream(s).point,a=l.translate([u-.205*e,f+.212*e]).clipExtent([[u-.214*e+kt,f+.166*e+kt],[u-.115*e-kt,f+.234*e-kt]]).stream(s).point,c},c.scale(1070)};var ln,sn,cn,un,fn,dn,pn={point:I,lineStart:I,lineEnd:I,polygonStart:function(){sn=0,pn.lineStart=hn},polygonEnd:function(){pn.lineStart=pn.lineEnd=pn.point=I,ln+=m(sn/2)}};function hn(){var t,e,r,n;function a(t,e){sn+=n*t-r*e,r=t,n=e}pn.point=function(i,o){pn.point=a,t=r=i,e=n=o},pn.lineEnd=function(){a(t,e)}}var gn={point:function(t,e){t<cn&&(cn=t);t>fn&&(fn=t);e<un&&(un=e);e>dn&&(dn=e)},lineStart:I,lineEnd:I,polygonStart:I,polygonEnd:I};function yn(){var t=vn(4.5),e=[],r={point:n,lineStart:function(){r.point=a},lineEnd:o,polygonStart:function(){r.lineEnd=l},polygonEnd:function(){r.lineEnd=o,r.point=n},pointRadius:function(e){return t=vn(e),r},result:function(){if(e.length){var t=e.join("");return e=[],t}}};function n(r,n){e.push("M",r,",",n,t)}function a(t,n){e.push("M",t,",",n),r.point=i}function i(t,r){e.push("L",t,",",r)}function o(){r.point=n}function l(){e.push("Z")}return r}function vn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}var mn,xn={point:bn,lineStart:_n,lineEnd:wn,polygonStart:function(){xn.lineStart=kn},polygonEnd:function(){xn.point=bn,xn.lineStart=_n,xn.lineEnd=wn}};function bn(t,e){xr+=t,br+=e,++_r}function _n(){var t,e;function r(r,n){var a=r-t,i=n-e,o=Math.sqrt(a*a+i*i);wr+=o*(t+r)/2,kr+=o*(e+n)/2,Mr+=o,bn(t=r,e=n)}xn.point=function(n,a){xn.point=r,bn(t=n,e=a)}}function wn(){xn.point=bn}function kn(){var t,e,r,n;function a(t,e){var a=t-r,i=e-n,o=Math.sqrt(a*a+i*i);wr+=o*(r+t)/2,kr+=o*(n+e)/2,Mr+=o,Tr+=(o=n*t-r*e)*(r+t),Ar+=o*(n+e),Lr+=3*o,bn(r=t,n=e)}xn.point=function(i,o){xn.point=a,bn(t=r=i,e=n=o)},xn.lineEnd=function(){a(t,e)}}function Mn(t){var e=4.5,r={point:n,lineStart:function(){r.point=a},lineEnd:o,polygonStart:function(){r.lineEnd=l},polygonEnd:function(){r.lineEnd=o,r.point=n},pointRadius:function(t){return e=t,r},result:I};function n(r,n){t.moveTo(r+e,n),t.arc(r,n,e,0,At)}function a(e,n){t.moveTo(e,n),r.point=i}function i(e,r){t.lineTo(e,r)}function o(){r.point=n}function l(){t.closePath()}return r}function Tn(t){var e=.5,r=Math.cos(30*St),n=16;function a(e){return(n?function(e){var r,a,o,l,s,c,u,f,d,p,h,g,y={point:v,lineStart:m,lineEnd:b,polygonStart:function(){e.polygonStart(),y.lineStart=_},polygonEnd:function(){e.polygonEnd(),y.lineStart=m}};function v(r,n){r=t(r,n),e.point(r[0],r[1])}function m(){f=NaN,y.point=x,e.lineStart()}function x(r,a){var o=Pr([r,a]),l=t(r,a);i(f,d,u,p,h,g,f=l[0],d=l[1],u=r,p=o[0],h=o[1],g=o[2],n,e),e.point(f,d)}function b(){y.point=v,e.lineEnd()}function _(){m(),y.point=w,y.lineEnd=k}function w(t,e){x(r=t,e),a=f,o=d,l=p,s=h,c=g,y.point=x}function k(){i(f,d,u,p,h,g,a,o,r,l,s,c,n,e),y.lineEnd=b,b()}return y}:function(e){return Ln(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})})(e)}function i(n,a,o,l,s,c,u,f,d,p,h,g,y,v){var x=u-n,b=f-a,_=x*x+b*b;if(_>4*e&&y--){var w=l+p,k=s+h,M=c+g,T=Math.sqrt(w*w+k*k+M*M),A=Math.asin(M/=T),L=m(m(M)-1)<kt||m(o-d)<kt?(o+d)/2:Math.atan2(k,w),C=t(L,A),S=C[0],O=C[1],P=S-n,D=O-a,z=b*P-x*D;(z*z/_>e||m((x*P+b*D)/_-.5)>.3||l*p+s*h+c*g<r)&&(i(n,a,o,l,s,c,S,O,L,w/=T,k/=T,M,y,v),v.point(S,O),i(S,O,L,w,k,M,u,f,d,p,h,g,y,v))}}return a.precision=function(t){return arguments.length?(n=(e=t*t)>0&&16,a):Math.sqrt(e)},a}function An(t){this.stream=t}function Ln(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function Cn(t){return Sn(function(){return t})()}function Sn(e){var r,n,a,i,o,l,s=Tn(function(t,e){return[(t=r(t,e))[0]*c+i,o-t[1]*c]}),c=150,u=480,f=250,d=0,p=0,h=0,g=0,y=0,v=tn,x=P,b=null,_=null;function w(t){return[(t=a(t[0]*St,t[1]*St))[0]*c+i,o-t[1]*c]}function k(t){return(t=a.invert((t[0]-i)/c,(o-t[1])/c))&&[t[0]*Ot,t[1]*Ot]}function M(){a=Gr(n=zn(h,g,y),r);var t=r(d,p);return i=u-t[0]*c,o=f+t[1]*c,T()}function T(){return l&&(l.valid=!1,l=null),w}return w.stream=function(t){return l&&(l.valid=!1),(l=On(v(n,s(x(t))))).valid=!0,l},w.clipAngle=function(t){return arguments.length?(v=null==t?(b=t,tn):function(t){var e=Math.cos(t),r=e>0,n=m(e)>kt;return Qr(a,function(t){var e,l,s,c,u;return{lineStart:function(){c=s=!1,u=1},point:function(f,d){var p,h=[f,d],g=a(f,d),y=r?g?0:o(f,d):g?o(f+(f<0?Tt:-Tt),d):0;if(!e&&(c=s=g)&&t.lineStart(),g!==s&&(p=i(e,h),(Fr(e,p)||Fr(h,p))&&(h[0]+=kt,h[1]+=kt,g=a(h[0],h[1]))),g!==s)u=0,g?(t.lineStart(),p=i(h,e),t.point(p[0],p[1])):(p=i(e,h),t.point(p[0],p[1]),t.lineEnd()),e=p;else if(n&&e&&r^g){var v;y&l||!(v=i(h,e,!0))||(u=0,r?(t.lineStart(),t.point(v[0][0],v[0][1]),t.point(v[1][0],v[1][1]),t.lineEnd()):(t.point(v[1][0],v[1][1]),t.lineEnd(),t.lineStart(),t.point(v[0][0],v[0][1])))}!g||e&&Fr(e,h)||t.point(h[0],h[1]),e=h,s=g,l=y},lineEnd:function(){s&&t.lineEnd(),e=null},clean:function(){return u|(c&&s)<<1}}},Rn(t,6*St),r?[0,-t]:[-Tt,t-Tt]);function a(t,r){return Math.cos(t)*Math.cos(r)>e}function i(t,r,n){var a=[1,0,0],i=zr(Pr(t),Pr(r)),o=Dr(i,i),l=i[0],s=o-l*l;if(!s)return!n&&t;var c=e*o/s,u=-e*l/s,f=zr(a,i),d=Ir(a,c);Er(d,Ir(i,u));var p=f,h=Dr(d,p),g=Dr(p,p),y=h*h-g*(Dr(d,d)-1);if(!(y<0)){var v=Math.sqrt(y),x=Ir(p,(-h-v)/g);if(Er(x,d),x=Rr(x),!n)return x;var b,_=t[0],w=r[0],k=t[1],M=r[1];w<_&&(b=_,_=w,w=b);var T=w-_,A=m(T-Tt)<kt;if(!A&&M<k&&(b=k,k=M,M=b),A||T<kt?A?k+M>0^x[1]<(m(x[0]-_)<kt?k:M):k<=x[1]&&x[1]<=M:T>Tt^(_<=x[0]&&x[0]<=w)){var L=Ir(p,(-h+v)/g);return Er(L,d),[x,Rr(L)]}}}function o(e,n){var a=r?t:Tt-t,i=0;return e<-a?i|=1:e>a&&(i|=2),n<-a?i|=4:n>a&&(i|=8),i}}((b=+t)*St),T()):b},w.clipExtent=function(t){return arguments.length?(_=t,x=t?nn(t[0][0],t[0][1],t[1][0],t[1][1]):P,T()):_},w.scale=function(t){return arguments.length?(c=+t,M()):c},w.translate=function(t){return arguments.length?(u=+t[0],f=+t[1],M()):[u,f]},w.center=function(t){return arguments.length?(d=t[0]%360*St,p=t[1]%360*St,M()):[d*Ot,p*Ot]},w.rotate=function(t){return arguments.length?(h=t[0]%360*St,g=t[1]%360*St,y=t.length>2?t[2]%360*St:0,M()):[h*Ot,g*Ot,y*Ot]},t.rebind(w,s,"precision"),function(){return r=e.apply(this,arguments),w.invert=r.invert&&k,M()}}function On(t){return Ln(t,function(e,r){t.point(e*St,r*St)})}function Pn(t,e){return[t,e]}function Dn(t,e){return[t>Tt?t-At:t<-Tt?t+At:t,e]}function zn(t,e,r){return t?e||r?Gr(In(t),Nn(e,r)):In(t):e||r?Nn(e,r):Dn}function En(t){return function(e,r){return[(e+=t)>Tt?e-At:e<-Tt?e+At:e,r]}}function In(t){var e=En(t);return e.invert=En(-t),e}function Nn(t,e){var r=Math.cos(t),n=Math.sin(t),a=Math.cos(e),i=Math.sin(e);function o(t,e){var o=Math.cos(e),l=Math.cos(t)*o,s=Math.sin(t)*o,c=Math.sin(e),u=c*r+l*n;return[Math.atan2(s*a-u*i,l*r-c*n),Et(u*a+s*i)]}return o.invert=function(t,e){var o=Math.cos(e),l=Math.cos(t)*o,s=Math.sin(t)*o,c=Math.sin(e),u=c*a-s*i;return[Math.atan2(s*a+c*i,l*r+u*n),Et(u*r-l*n)]},o}function Rn(t,e){var r=Math.cos(t),n=Math.sin(t);return function(a,i,o,l){var s=o*e;null!=a?(a=Fn(r,a),i=Fn(r,i),(o>0?a<i:a>i)&&(a+=o*At)):(a=t+o*At,i=t-.5*s);for(var c,u=a;o>0?u>i:u<i;u-=s)l.point((c=Rr([r,-n*Math.cos(u),-n*Math.sin(u)]))[0],c[1])}}function Fn(t,e){var r=Pr(e);r[0]-=t,Nr(r);var n=zt(-r[1]);return((-r[2]<0?-n:n)+2*Math.PI-kt)%(2*Math.PI)}function jn(e,r,n){var a=t.range(e,r-kt,n).concat(r);return function(t){return a.map(function(e){return[t,e]})}}function Bn(e,r,n){var a=t.range(e,r-kt,n).concat(r);return function(t){return a.map(function(e){return[e,t]})}}function Hn(t){return t.source}function qn(t){return t.target}t.geo.path=function(){var e,r,n,a,i,o=4.5;function l(e){return e&&("function"==typeof o&&a.pointRadius(+o.apply(this,arguments)),i&&i.valid||(i=n(a)),t.geo.stream(e,i)),a.result()}function s(){return i=null,l}return l.area=function(e){return ln=0,t.geo.stream(e,n(pn)),ln},l.centroid=function(e){return xr=br=_r=wr=kr=Mr=Tr=Ar=Lr=0,t.geo.stream(e,n(xn)),Lr?[Tr/Lr,Ar/Lr]:Mr?[wr/Mr,kr/Mr]:_r?[xr/_r,br/_r]:[NaN,NaN]},l.bounds=function(e){return fn=dn=-(cn=un=1/0),t.geo.stream(e,n(gn)),[[cn,un],[fn,dn]]},l.projection=function(t){return arguments.length?(n=(e=t)?t.stream||(r=t,a=Tn(function(t,e){return r([t*Ot,e*Ot])}),function(t){return On(a(t))}):P,s()):e;var r,a},l.context=function(t){return arguments.length?(a=null==(r=t)?new yn:new Mn(t),"function"!=typeof o&&a.pointRadius(o),s()):r},l.pointRadius=function(t){return arguments.length?(o="function"==typeof t?t:(a.pointRadius(+t),+t),l):o},l.projection(t.geo.albersUsa()).context(null)},t.geo.transform=function(t){return{stream:function(e){var r=new An(e);for(var n in t)r[n]=t[n];return r}}},An.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},t.geo.projection=Cn,t.geo.projectionMutator=Sn,(t.geo.equirectangular=function(){return Cn(Pn)}).raw=Pn.invert=Pn,t.geo.rotation=function(t){function e(e){return(e=t(e[0]*St,e[1]*St))[0]*=Ot,e[1]*=Ot,e}return t=zn(t[0]%360*St,t[1]*St,t.length>2?t[2]*St:0),e.invert=function(e){return(e=t.invert(e[0]*St,e[1]*St))[0]*=Ot,e[1]*=Ot,e},e},Dn.invert=Pn,t.geo.circle=function(){var t,e,r=[0,0],n=6;function a(){var t="function"==typeof r?r.apply(this,arguments):r,n=zn(-t[0]*St,-t[1]*St,0).invert,a=[];return e(null,null,1,{point:function(t,e){a.push(t=n(t,e)),t[0]*=Ot,t[1]*=Ot}}),{type:"Polygon",coordinates:[a]}}return a.origin=function(t){return arguments.length?(r=t,a):r},a.angle=function(r){return arguments.length?(e=Rn((t=+r)*St,n*St),a):t},a.precision=function(r){return arguments.length?(e=Rn(t*St,(n=+r)*St),a):n},a.angle(90)},t.geo.distance=function(t,e){var r,n=(e[0]-t[0])*St,a=t[1]*St,i=e[1]*St,o=Math.sin(n),l=Math.cos(n),s=Math.sin(a),c=Math.cos(a),u=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((r=f*o)*r+(r=c*u-s*f*l)*r),s*u+c*f*l)},t.geo.graticule=function(){var e,r,n,a,i,o,l,s,c,u,f,d,p=10,h=p,g=90,y=360,v=2.5;function x(){return{type:"MultiLineString",coordinates:b()}}function b(){return t.range(Math.ceil(a/g)*g,n,g).map(f).concat(t.range(Math.ceil(s/y)*y,l,y).map(d)).concat(t.range(Math.ceil(r/p)*p,e,p).filter(function(t){return m(t%g)>kt}).map(c)).concat(t.range(Math.ceil(o/h)*h,i,h).filter(function(t){return m(t%y)>kt}).map(u))}return x.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},x.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(n).reverse().slice(1),d(s).reverse().slice(1))]}},x.extent=function(t){return arguments.length?x.majorExtent(t).minorExtent(t):x.minorExtent()},x.majorExtent=function(t){return arguments.length?(a=+t[0][0],n=+t[1][0],s=+t[0][1],l=+t[1][1],a>n&&(t=a,a=n,n=t),s>l&&(t=s,s=l,l=t),x.precision(v)):[[a,s],[n,l]]},x.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],o=+t[0][1],i=+t[1][1],r>e&&(t=r,r=e,e=t),o>i&&(t=o,o=i,i=t),x.precision(v)):[[r,o],[e,i]]},x.step=function(t){return arguments.length?x.majorStep(t).minorStep(t):x.minorStep()},x.majorStep=function(t){return arguments.length?(g=+t[0],y=+t[1],x):[g,y]},x.minorStep=function(t){return arguments.length?(p=+t[0],h=+t[1],x):[p,h]},x.precision=function(t){return arguments.length?(v=+t,c=jn(o,i,90),u=Bn(r,e,v),f=jn(s,l,90),d=Bn(a,n,v),x):v},x.majorExtent([[-180,-90+kt],[180,90-kt]]).minorExtent([[-180,-80-kt],[180,80+kt]])},t.geo.greatArc=function(){var e,r,n=Hn,a=qn;function i(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||a.apply(this,arguments)]}}return i.distance=function(){return t.geo.distance(e||n.apply(this,arguments),r||a.apply(this,arguments))},i.source=function(t){return arguments.length?(n=t,e="function"==typeof t?null:t,i):n},i.target=function(t){return arguments.length?(a=t,r="function"==typeof t?null:t,i):a},i.precision=function(){return arguments.length?i:0},i},t.geo.interpolate=function(t,e){return r=t[0]*St,n=t[1]*St,a=e[0]*St,i=e[1]*St,o=Math.cos(n),l=Math.sin(n),s=Math.cos(i),c=Math.sin(i),u=o*Math.cos(r),f=o*Math.sin(r),d=s*Math.cos(a),p=s*Math.sin(a),h=2*Math.asin(Math.sqrt(Nt(i-n)+o*s*Nt(a-r))),g=1/Math.sin(h),(y=h?function(t){var e=Math.sin(t*=h)*g,r=Math.sin(h-t)*g,n=r*u+e*d,a=r*f+e*p,i=r*l+e*c;return[Math.atan2(a,n)*Ot,Math.atan2(i,Math.sqrt(n*n+a*a))*Ot]}:function(){return[r*Ot,n*Ot]}).distance=h,y;var r,n,a,i,o,l,s,c,u,f,d,p,h,g,y},t.geo.length=function(e){return mn=0,t.geo.stream(e,Vn),mn};var Vn={sphere:I,point:I,lineStart:function(){var t,e,r;function n(n,a){var i=Math.sin(a*=St),o=Math.cos(a),l=m((n*=St)-t),s=Math.cos(l);mn+=Math.atan2(Math.sqrt((l=o*Math.sin(l))*l+(l=r*i-e*o*s)*l),e*i+r*o*s),t=n,e=i,r=o}Vn.point=function(a,i){t=a*St,e=Math.sin(i*=St),r=Math.cos(i),Vn.point=n},Vn.lineEnd=function(){Vn.point=Vn.lineEnd=I}},lineEnd:I,polygonStart:I,polygonEnd:I};function Un(t,e){function r(e,r){var n=Math.cos(e),a=Math.cos(r),i=t(n*a);return[i*a*Math.sin(e),i*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),a=e(n),i=Math.sin(a),o=Math.cos(a);return[Math.atan2(t*i,n*o),Math.asin(n&&r*i/n)]},r}var Gn=Un(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(t.geo.azimuthalEqualArea=function(){return Cn(Gn)}).raw=Gn;var Yn=Un(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},P);function Xn(t,e){var r=Math.cos(t),n=function(t){return Math.tan(Tt/4+t/2)},a=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(n(e)/n(t)),i=r*Math.pow(n(t),a)/a;if(!a)return Qn;function o(t,e){i>0?e<-Ct+kt&&(e=-Ct+kt):e>Ct-kt&&(e=Ct-kt);var r=i/Math.pow(n(e),a);return[r*Math.sin(a*t),i-r*Math.cos(a*t)]}return o.invert=function(t,e){var r=i-e,n=Pt(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(i/n,1/a))-Ct]},o}function Zn(t,e){var r=Math.cos(t),n=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),a=r/n+t;if(m(n)<kt)return Pn;function i(t,e){var r=a-e;return[r*Math.sin(n*t),a-r*Math.cos(n*t)]}return i.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/n,a-Pt(n)*Math.sqrt(t*t+r*r)]},i}(t.geo.azimuthalEquidistant=function(){return Cn(Yn)}).raw=Yn,(t.geo.conicConformal=function(){return an(Xn)}).raw=Xn,(t.geo.conicEquidistant=function(){return an(Zn)}).raw=Zn;var Wn=Un(function(t){return 1/t},Math.atan);function Qn(t,e){return[t,Math.log(Math.tan(Tt/4+e/2))]}function Jn(t){var e,r=Cn(t),n=r.scale,a=r.translate,i=r.clipExtent;return r.scale=function(){var t=n.apply(r,arguments);return t===r?e?r.clipExtent(null):r:t},r.translate=function(){var t=a.apply(r,arguments);return t===r?e?r.clipExtent(null):r:t},r.clipExtent=function(t){var o=i.apply(r,arguments);if(o===r){if(e=null==t){var l=Tt*n(),s=a();i([[s[0]-l,s[1]-l],[s[0]+l,s[1]+l]])}}else e&&(o=null);return o},r.clipExtent(null)}(t.geo.gnomonic=function(){return Cn(Wn)}).raw=Wn,Qn.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Ct]},(t.geo.mercator=function(){return Jn(Qn)}).raw=Qn;var $n=Un(function(){return 1},Math.asin);(t.geo.orthographic=function(){return Cn($n)}).raw=$n;var Kn=Un(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});function ta(t,e){return[Math.log(Math.tan(Tt/4+e/2)),-t]}function ea(t){return t[0]}function ra(t){return t[1]}function na(t){for(var e=t.length,r=[0,1],n=2,a=2;a<e;a++){for(;n>1&&Dt(t[r[n-2]],t[r[n-1]],t[a])<=0;)--n;r[n++]=a}return r.slice(0,n)}function aa(t,e){return t[0]-e[0]||t[1]-e[1]}(t.geo.stereographic=function(){return Cn(Kn)}).raw=Kn,ta.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ct]},(t.geo.transverseMercator=function(){var t=Jn(ta),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):[(t=e())[1],-t[0]]},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):[(t=r())[0],t[1],t[2]-90]},r([0,0,90])}).raw=ta,t.geom={},t.geom.hull=function(t){var e=ea,r=ra;if(arguments.length)return n(t);function n(t){if(t.length<3)return[];var n,a=ye(e),i=ye(r),o=t.length,l=[],s=[];for(n=0;n<o;n++)l.push([+a.call(this,t[n],n),+i.call(this,t[n],n),n]);for(l.sort(aa),n=0;n<o;n++)s.push([l[n][0],-l[n][1]]);var c=na(l),u=na(s),f=u[0]===c[0],d=u[u.length-1]===c[c.length-1],p=[];for(n=c.length-1;n>=0;--n)p.push(t[l[c[n]][2]]);for(n=+f;n<u.length-d;++n)p.push(t[l[u[n]][2]]);return p}return n.x=function(t){return arguments.length?(e=t,n):e},n.y=function(t){return arguments.length?(r=t,n):r},n},t.geom.polygon=function(t){return q(t,ia),t};var ia=t.geom.polygon.prototype=[];function oa(t,e,r){return(r[0]-e[0])*(t[1]-e[1])<(r[1]-e[1])*(t[0]-e[0])}function la(t,e,r,n){var a=t[0],i=r[0],o=e[0]-a,l=n[0]-i,s=t[1],c=r[1],u=e[1]-s,f=n[1]-c,d=(l*(s-c)-f*(a-i))/(f*o-l*u);return[a+d*o,s+d*u]}function sa(t){var e=t[0],r=t[t.length-1];return!(e[0]-r[0]||e[1]-r[1])}ia.area=function(){for(var t,e=-1,r=this.length,n=this[r-1],a=0;++e<r;)t=n,n=this[e],a+=t[1]*n[0]-t[0]*n[1];return.5*a},ia.centroid=function(t){var e,r,n=-1,a=this.length,i=0,o=0,l=this[a-1];for(arguments.length||(t=-1/(6*this.area()));++n<a;)e=l,l=this[n],r=e[0]*l[1]-l[0]*e[1],i+=(e[0]+l[0])*r,o+=(e[1]+l[1])*r;return[i*t,o*t]},ia.clip=function(t){for(var e,r,n,a,i,o,l=sa(t),s=-1,c=this.length-sa(this),u=this[c-1];++s<c;){for(e=t.slice(),t.length=0,a=this[s],i=e[(n=e.length-l)-1],r=-1;++r<n;)oa(o=e[r],u,a)?(oa(i,u,a)||t.push(la(i,o,u,a)),t.push(o)):oa(i,u,a)&&t.push(la(i,o,u,a)),i=o;l&&t.push(t[0]),u=a}return t};var ca,ua,fa,da,pa,ha=[],ga=[];function ya(){Ea(this),this.edge=this.site=this.circle=null}function va(t){var e=ha.pop()||new ya;return e.site=t,e}function ma(t){La(t),fa.remove(t),ha.push(t),Ea(t)}function xa(t){var e=t.circle,r=e.x,n=e.cy,a={x:r,y:n},i=t.P,o=t.N,l=[t];ma(t);for(var s=i;s.circle&&m(r-s.circle.x)<kt&&m(n-s.circle.cy)<kt;)i=s.P,l.unshift(s),ma(s),s=i;l.unshift(s),La(s);for(var c=o;c.circle&&m(r-c.circle.x)<kt&&m(n-c.circle.cy)<kt;)o=c.N,l.push(c),ma(c),c=o;l.push(c),La(c);var u,f=l.length;for(u=1;u<f;++u)c=l[u],s=l[u-1],Pa(c.edge,s.site,c.site,a);s=l[0],(c=l[f-1]).edge=Oa(s.site,c.site,null,a),Aa(s),Aa(c)}function ba(t){for(var e,r,n,a,i=t.x,o=t.y,l=fa._;l;)if((n=_a(l,o)-i)>kt)l=l.L;else{if(!((a=i-wa(l,o))>kt)){n>-kt?(e=l.P,r=l):a>-kt?(e=l,r=l.N):e=r=l;break}if(!l.R){e=l;break}l=l.R}var s=va(t);if(fa.insert(e,s),e||r){if(e===r)return La(e),r=va(e.site),fa.insert(s,r),s.edge=r.edge=Oa(e.site,s.site),Aa(e),void Aa(r);if(r){La(e),La(r);var c=e.site,u=c.x,f=c.y,d=t.x-u,p=t.y-f,h=r.site,g=h.x-u,y=h.y-f,v=2*(d*y-p*g),m=d*d+p*p,x=g*g+y*y,b={x:(y*m-p*x)/v+u,y:(d*x-g*m)/v+f};Pa(r.edge,c,h,b),s.edge=Oa(c,t,null,b),r.edge=Oa(t,h,null,b),Aa(e),Aa(r)}else s.edge=Oa(e.site,s.site)}}function _a(t,e){var r=t.site,n=r.x,a=r.y,i=a-e;if(!i)return n;var o=t.P;if(!o)return-1/0;var l=(r=o.site).x,s=r.y,c=s-e;if(!c)return l;var u=l-n,f=1/i-1/c,d=u/c;return f?(-d+Math.sqrt(d*d-2*f*(u*u/(-2*c)-s+c/2+a-i/2)))/f+n:(n+l)/2}function wa(t,e){var r=t.N;if(r)return _a(r,e);var n=t.site;return n.y===e?n.x:1/0}function ka(t){this.site=t,this.edges=[]}function Ma(t,e){return e.angle-t.angle}function Ta(){Ea(this),this.x=this.y=this.arc=this.site=this.cy=null}function Aa(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,a=t.site,i=r.site;if(n!==i){var o=a.x,l=a.y,s=n.x-o,c=n.y-l,u=i.x-o,f=2*(s*(y=i.y-l)-c*u);if(!(f>=-Mt)){var d=s*s+c*c,p=u*u+y*y,h=(y*d-c*p)/f,g=(s*p-u*d)/f,y=g+l,v=ga.pop()||new Ta;v.arc=t,v.site=a,v.x=h+o,v.y=y+Math.sqrt(h*h+g*g),v.cy=y,t.circle=v;for(var m=null,x=pa._;x;)if(v.y<x.y||v.y===x.y&&v.x<=x.x){if(!x.L){m=x.P;break}x=x.L}else{if(!x.R){m=x;break}x=x.R}pa.insert(m,v),m||(da=v)}}}}function La(t){var e=t.circle;e&&(e.P||(da=e.N),pa.remove(e),ga.push(e),Ea(e),t.circle=null)}function Ca(t,e){var r=t.b;if(r)return!0;var n,a,i=t.a,o=e[0][0],l=e[1][0],s=e[0][1],c=e[1][1],u=t.l,f=t.r,d=u.x,p=u.y,h=f.x,g=f.y,y=(d+h)/2,v=(p+g)/2;if(g===p){if(y<o||y>=l)return;if(d>h){if(i){if(i.y>=c)return}else i={x:y,y:s};r={x:y,y:c}}else{if(i){if(i.y<s)return}else i={x:y,y:c};r={x:y,y:s}}}else if(a=v-(n=(d-h)/(g-p))*y,n<-1||n>1)if(d>h){if(i){if(i.y>=c)return}else i={x:(s-a)/n,y:s};r={x:(c-a)/n,y:c}}else{if(i){if(i.y<s)return}else i={x:(c-a)/n,y:c};r={x:(s-a)/n,y:s}}else if(p<g){if(i){if(i.x>=l)return}else i={x:o,y:n*o+a};r={x:l,y:n*l+a}}else{if(i){if(i.x<o)return}else i={x:l,y:n*l+a};r={x:o,y:n*o+a}}return t.a=i,t.b=r,!0}function Sa(t,e){this.l=t,this.r=e,this.a=this.b=null}function Oa(t,e,r,n){var a=new Sa(t,e);return ca.push(a),r&&Pa(a,t,e,r),n&&Pa(a,e,t,n),ua[t.i].edges.push(new Da(a,t,e)),ua[e.i].edges.push(new Da(a,e,t)),a}function Pa(t,e,r,n){t.a||t.b?t.l===r?t.b=n:t.a=n:(t.a=n,t.l=e,t.r=r)}function Da(t,e,r){var n=t.a,a=t.b;this.edge=t,this.site=e,this.angle=r?Math.atan2(r.y-e.y,r.x-e.x):t.l===e?Math.atan2(a.x-n.x,n.y-a.y):Math.atan2(n.x-a.x,a.y-n.y)}function za(){this._=null}function Ea(t){t.U=t.C=t.L=t.R=t.P=t.N=null}function Ia(t,e){var r=e,n=e.R,a=r.U;a?a.L===r?a.L=n:a.R=n:t._=n,n.U=a,r.U=n,r.R=n.L,r.R&&(r.R.U=r),n.L=r}function Na(t,e){var r=e,n=e.L,a=r.U;a?a.L===r?a.L=n:a.R=n:t._=n,n.U=a,r.U=n,r.L=n.R,r.L&&(r.L.U=r),n.R=r}function Ra(t){for(;t.L;)t=t.L;return t}function Fa(t,e){var r,n,a,i=t.sort(ja).pop();for(ca=[],ua=new Array(t.length),fa=new za,pa=new za;;)if(a=da,i&&(!a||i.y<a.y||i.y===a.y&&i.x<a.x))i.x===r&&i.y===n||(ua[i.i]=new ka(i),ba(i),r=i.x,n=i.y),i=t.pop();else{if(!a)break;xa(a.arc)}e&&(function(t){for(var e,r=ca,n=en(t[0][0],t[0][1],t[1][0],t[1][1]),a=r.length;a--;)(!Ca(e=r[a],t)||!n(e)||m(e.a.x-e.b.x)<kt&&m(e.a.y-e.b.y)<kt)&&(e.a=e.b=null,r.splice(a,1))}(e),function(t){for(var e,r,n,a,i,o,l,s,c,u,f=t[0][0],d=t[1][0],p=t[0][1],h=t[1][1],g=ua,y=g.length;y--;)if((i=g[y])&&i.prepare())for(s=(l=i.edges).length,o=0;o<s;)n=(u=l[o].end()).x,a=u.y,e=(c=l[++o%s].start()).x,r=c.y,(m(n-e)>kt||m(a-r)>kt)&&(l.splice(o,0,new Da((v=i.site,x=u,b=m(n-f)<kt&&h-a>kt?{x:f,y:m(e-f)<kt?r:h}:m(a-h)<kt&&d-n>kt?{x:m(r-h)<kt?e:d,y:h}:m(n-d)<kt&&a-p>kt?{x:d,y:m(e-d)<kt?r:p}:m(a-p)<kt&&n-f>kt?{x:m(r-p)<kt?e:f,y:p}:null,_=void 0,_=new Sa(v,null),_.a=x,_.b=b,ca.push(_),_),i.site,null)),++s);var v,x,b,_}(e));var o={cells:ua,edges:ca};return fa=pa=ca=ua=null,o}function ja(t,e){return e.y-t.y||e.x-t.x}ka.prototype.prepare=function(){for(var t,e=this.edges,r=e.length;r--;)(t=e[r].edge).b&&t.a||e.splice(r,1);return e.sort(Ma),e.length},Da.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}},za.prototype={insert:function(t,e){var r,n,a;if(t){if(e.P=t,e.N=t.N,t.N&&(t.N.P=e),t.N=e,t.R){for(t=t.R;t.L;)t=t.L;t.L=e}else t.R=e;r=t}else this._?(t=Ra(this._),e.P=null,e.N=t,t.P=t.L=e,r=t):(e.P=e.N=null,this._=e,r=null);for(e.L=e.R=null,e.U=r,e.C=!0,t=e;r&&r.C;)r===(n=r.U).L?(a=n.R)&&a.C?(r.C=a.C=!1,n.C=!0,t=n):(t===r.R&&(Ia(this,r),r=(t=r).U),r.C=!1,n.C=!0,Na(this,n)):(a=n.L)&&a.C?(r.C=a.C=!1,n.C=!0,t=n):(t===r.L&&(Na(this,r),r=(t=r).U),r.C=!1,n.C=!0,Ia(this,n)),r=t.U;this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P),t.P&&(t.P.N=t.N),t.N=t.P=null;var e,r,n,a=t.U,i=t.L,o=t.R;if(r=i?o?Ra(o):i:o,a?a.L===t?a.L=r:a.R=r:this._=r,i&&o?(n=r.C,r.C=t.C,r.L=i,i.U=r,r!==o?(a=r.U,r.U=t.U,t=r.R,a.L=t,r.R=o,o.U=r):(r.U=a,a=r,t=r.R)):(n=t.C,t=r),t&&(t.U=a),!n)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===a.L){if((e=a.R).C&&(e.C=!1,a.C=!0,Ia(this,a),e=a.R),e.L&&e.L.C||e.R&&e.R.C){e.R&&e.R.C||(e.L.C=!1,e.C=!0,Na(this,e),e=a.R),e.C=a.C,a.C=e.R.C=!1,Ia(this,a),t=this._;break}}else if((e=a.L).C&&(e.C=!1,a.C=!0,Na(this,a),e=a.L),e.L&&e.L.C||e.R&&e.R.C){e.L&&e.L.C||(e.R.C=!1,e.C=!0,Ia(this,e),e=a.L),e.C=a.C,a.C=e.L.C=!1,Na(this,a),t=this._;break}e.C=!0,t=a,a=a.U}while(!t.C);t&&(t.C=!1)}}},t.geom.voronoi=function(t){var e=ea,r=ra,n=e,a=r,i=Ba;if(t)return o(t);function o(t){var e=new Array(t.length),r=i[0][0],n=i[0][1],a=i[1][0],o=i[1][1];return Fa(l(t),i).cells.forEach(function(i,l){var s=i.edges,c=i.site;(e[l]=s.length?s.map(function(t){var e=t.start();return[e.x,e.y]}):c.x>=r&&c.x<=a&&c.y>=n&&c.y<=o?[[r,o],[a,o],[a,n],[r,n]]:[]).point=t[l]}),e}function l(t){return t.map(function(t,e){return{x:Math.round(n(t,e)/kt)*kt,y:Math.round(a(t,e)/kt)*kt,i:e}})}return o.links=function(t){return Fa(l(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},o.triangles=function(t){var e=[];return Fa(l(t)).cells.forEach(function(r,n){for(var a,i,o,l,s=r.site,c=r.edges.sort(Ma),u=-1,f=c.length,d=c[f-1].edge,p=d.l===s?d.r:d.l;++u<f;)d,a=p,p=(d=c[u].edge).l===s?d.r:d.l,n<a.i&&n<p.i&&(o=a,l=p,((i=s).x-l.x)*(o.y-i.y)-(i.x-o.x)*(l.y-i.y)<0)&&e.push([t[n],t[a.i],t[p.i]])}),e},o.x=function(t){return arguments.length?(n=ye(e=t),o):e},o.y=function(t){return arguments.length?(a=ye(r=t),o):r},o.clipExtent=function(t){return arguments.length?(i=null==t?Ba:t,o):i===Ba?null:i},o.size=function(t){return arguments.length?o.clipExtent(t&&[[0,0],t]):i===Ba?null:i&&i[1]},o};var Ba=[[-1e6,-1e6],[1e6,1e6]];function Ha(t){return t.x}function qa(t){return t.y}function Va(e,r){e=t.rgb(e),r=t.rgb(r);var n=e.r,a=e.g,i=e.b,o=r.r-n,l=r.g-a,s=r.b-i;return function(t){return"#"+ce(Math.round(n+o*t))+ce(Math.round(a+l*t))+ce(Math.round(i+s*t))}}function Ua(t,e){var r,n={},a={};for(r in t)r in e?n[r]=Wa(t[r],e[r]):a[r]=t[r];for(r in e)r in t||(a[r]=e[r]);return function(t){for(r in n)a[r]=n[r](t);return a}}function Ga(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function Ya(t,e){var r,n,a,i=Xa.lastIndex=Za.lastIndex=0,o=-1,l=[],s=[];for(t+="",e+="";(r=Xa.exec(t))&&(n=Za.exec(e));)(a=n.index)>i&&(a=e.slice(i,a),l[o]?l[o]+=a:l[++o]=a),(r=r[0])===(n=n[0])?l[o]?l[o]+=n:l[++o]=n:(l[++o]=null,s.push({i:o,x:Ga(r,n)})),i=Za.lastIndex;return i<e.length&&(a=e.slice(i),l[o]?l[o]+=a:l[++o]=a),l.length<2?s[0]?(e=s[0].x,function(t){return e(t)+""}):function(){return e}:(e=s.length,function(t){for(var r,n=0;n<e;++n)l[(r=s[n]).i]=r.x(t);return l.join("")})}t.geom.delaunay=function(e){return t.geom.voronoi().triangles(e)},t.geom.quadtree=function(t,e,r,n,a){var i,o=ea,l=ra;if(i=arguments.length)return o=Ha,l=qa,3===i&&(a=r,n=e,r=e=0),s(t);function s(t){var s,c,u,f,d,p,h,g,y,v=ye(o),x=ye(l);if(null!=e)p=e,h=r,g=n,y=a;else if(g=y=-(p=h=1/0),c=[],u=[],d=t.length,i)for(f=0;f<d;++f)(s=t[f]).x<p&&(p=s.x),s.y<h&&(h=s.y),s.x>g&&(g=s.x),s.y>y&&(y=s.y),c.push(s.x),u.push(s.y);else for(f=0;f<d;++f){var b=+v(s=t[f],f),_=+x(s,f);b<p&&(p=b),_<h&&(h=_),b>g&&(g=b),_>y&&(y=_),c.push(b),u.push(_)}var w=g-p,k=y-h;function M(t,e,r,n,a,i,o,l){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var s=t.x,c=t.y;if(null!=s)if(m(s-r)+m(c-n)<.01)T(t,e,r,n,a,i,o,l);else{var u=t.point;t.x=t.y=t.point=null,T(t,u,s,c,a,i,o,l),T(t,e,r,n,a,i,o,l)}else t.x=r,t.y=n,t.point=e}else T(t,e,r,n,a,i,o,l)}function T(t,e,r,n,a,i,o,l){var s=.5*(a+o),c=.5*(i+l),u=r>=s,f=n>=c,d=f<<1|u;t.leaf=!1,u?a=s:o=s,f?i=c:l=c,M(t=t.nodes[d]||(t.nodes[d]={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(A,t,+v(t,++f),+x(t,f),p,h,g,y)}}),e,r,n,a,i,o,l)}w>k?y=h+w:g=p+k;var A={leaf:!0,nodes:[],point:null,x:null,y:null,add:function(t){M(A,t,+v(t,++f),+x(t,f),p,h,g,y)}};if(A.visit=function(t){!function t(e,r,n,a,i,o){if(!e(r,n,a,i,o)){var l=.5*(n+i),s=.5*(a+o),c=r.nodes;c[0]&&t(e,c[0],n,a,l,s),c[1]&&t(e,c[1],l,a,i,s),c[2]&&t(e,c[2],n,s,l,o),c[3]&&t(e,c[3],l,s,i,o)}}(t,A,p,h,g,y)},A.find=function(t){return function(t,e,r,n,a,i,o){var l,s=1/0;return function t(c,u,f,d,p){if(!(u>i||f>o||d<n||p<a)){if(h=c.point){var h,g=e-c.x,y=r-c.y,v=g*g+y*y;if(v<s){var m=Math.sqrt(s=v);n=e-m,a=r-m,i=e+m,o=r+m,l=h}}for(var x=c.nodes,b=.5*(u+d),_=.5*(f+p),w=(r>=_)<<1|e>=b,k=w+4;w<k;++w)if(c=x[3&w])switch(3&w){case 0:t(c,u,f,b,_);break;case 1:t(c,b,f,d,_);break;case 2:t(c,u,_,b,p);break;case 3:t(c,b,_,d,p)}}}(t,n,a,i,o),l}(A,t[0],t[1],p,h,g,y)},f=-1,null==e){for(;++f<d;)M(A,t[f],c[f],u[f],p,h,g,y);--f}else t.forEach(A.add);return c=u=t=s=null,A}return s.x=function(t){return arguments.length?(o=t,s):o},s.y=function(t){return arguments.length?(l=t,s):l},s.extent=function(t){return arguments.length?(null==t?e=r=n=a=null:(e=+t[0][0],r=+t[0][1],n=+t[1][0],a=+t[1][1]),s):null==e?null:[[e,r],[n,a]]},s.size=function(t){return arguments.length?(null==t?e=r=n=a=null:(e=r=0,n=+t[0],a=+t[1]),s):null==e?null:[n-e,a-r]},s},t.interpolateRgb=Va,t.interpolateObject=Ua,t.interpolateNumber=Ga,t.interpolateString=Ya;var Xa=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Za=new RegExp(Xa.source,"g");function Wa(e,r){for(var n,a=t.interpolators.length;--a>=0&&!(n=t.interpolators[a](e,r)););return n}function Qa(t,e){var r,n=[],a=[],i=t.length,o=e.length,l=Math.min(t.length,e.length);for(r=0;r<l;++r)n.push(Wa(t[r],e[r]));for(;r<i;++r)a[r]=t[r];for(;r<o;++r)a[r]=e[r];return function(t){for(r=0;r<l;++r)a[r]=n[r](t);return a}}t.interpolate=Wa,t.interpolators=[function(t,e){var r=typeof e;return("string"===r?ge.has(e.toLowerCase())||/^(#|rgb\(|hsl\()/i.test(e)?Va:Ya:e instanceof Ht?Va:Array.isArray(e)?Qa:"object"===r&&isNaN(e)?Ua:Ga)(t,e)}],t.interpolateArray=Qa;var Ja=function(){return P},$a=t.map({linear:Ja,poly:function(t){return function(e){return Math.pow(e,t)}},quad:function(){return ri},cubic:function(){return ni},sin:function(){return ii},exp:function(){return oi},circle:function(){return li},elastic:function(t,e){var r;arguments.length<2&&(e=.45);arguments.length?r=e/At*Math.asin(1/t):(t=1,r=e/4);return function(n){return 1+t*Math.pow(2,-10*n)*Math.sin((n-r)*At/e)}},back:function(t){t||(t=1.70158);return function(e){return e*e*((t+1)*e-t)}},bounce:function(){return si}}),Ka=t.map({in:P,out:ti,"in-out":ei,"out-in":function(t){return ei(ti(t))}});function ti(t){return function(e){return 1-t(1-e)}}function ei(t){return function(e){return.5*(e<.5?t(2*e):2-t(2-2*e))}}function ri(t){return t*t}function ni(t){return t*t*t}function ai(t){if(t<=0)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}function ii(t){return 1-Math.cos(t*Ct)}function oi(t){return Math.pow(2,10*(t-1))}function li(t){return 1-Math.sqrt(1-t*t)}function si(t){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}function ci(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function ui(t){var e,r,n,a=[t.a,t.b],i=[t.c,t.d],o=di(a),l=fi(a,i),s=di(((e=i)[0]+=(n=-l)*(r=a)[0],e[1]+=n*r[1],e))||0;a[0]*i[1]<i[0]*a[1]&&(a[0]*=-1,a[1]*=-1,o*=-1,l*=-1),this.rotate=(o?Math.atan2(a[1],a[0]):Math.atan2(-i[0],i[1]))*Ot,this.translate=[t.e,t.f],this.scale=[o,s],this.skew=s?Math.atan2(l,s)*Ot:0}function fi(t,e){return t[0]*e[0]+t[1]*e[1]}function di(t){var e=Math.sqrt(fi(t,t));return e&&(t[0]/=e,t[1]/=e),e}t.ease=function(t){var e,n=t.indexOf("-"),a=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1):"in";return a=$a.get(a)||Ja,i=Ka.get(i)||P,e=i(a.apply(null,r.call(arguments,1))),function(t){return t<=0?0:t>=1?1:e(t)}},t.interpolateHcl=function(e,r){e=t.hcl(e),r=t.hcl(r);var n=e.h,a=e.c,i=e.l,o=r.h-n,l=r.c-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.c:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Xt(n+o*t,a+l*t,i+s*t)+""}},t.interpolateHsl=function(e,r){e=t.hsl(e),r=t.hsl(r);var n=e.h,a=e.s,i=e.l,o=r.h-n,l=r.s-a,s=r.l-i;isNaN(l)&&(l=0,a=isNaN(a)?r.s:a);isNaN(o)?(o=0,n=isNaN(n)?r.h:n):o>180?o-=360:o<-180&&(o+=360);return function(t){return Ut(n+o*t,a+l*t,i+s*t)+""}},t.interpolateLab=function(e,r){e=t.lab(e),r=t.lab(r);var n=e.l,a=e.a,i=e.b,o=r.l-n,l=r.a-a,s=r.b-i;return function(t){return te(n+o*t,a+l*t,i+s*t)+""}},t.interpolateRound=ci,t.transform=function(e){var r=a.createElementNS(t.ns.prefix.svg,"g");return(t.transform=function(t){if(null!=t){r.setAttribute("transform",t);var e=r.transform.baseVal.consolidate()}return new ui(e?e.matrix:pi)})(e)},ui.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var pi={a:1,b:0,c:0,d:1,e:0,f:0};function hi(t){return t.length?t.pop()+",":""}function gi(e,r){var n=[],a=[];return e=t.transform(e),r=t.transform(r),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var a=r.push("translate(",null,",",null,")");n.push({i:a-4,x:Ga(t[0],e[0])},{i:a-2,x:Ga(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}(e.translate,r.translate,n,a),function(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(hi(r)+"rotate(",null,")")-2,x:Ga(t,e)})):e&&r.push(hi(r)+"rotate("+e+")")}(e.rotate,r.rotate,n,a),function(t,e,r,n){t!==e?n.push({i:r.push(hi(r)+"skewX(",null,")")-2,x:Ga(t,e)}):e&&r.push(hi(r)+"skewX("+e+")")}(e.skew,r.skew,n,a),function(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var a=r.push(hi(r)+"scale(",null,",",null,")");n.push({i:a-4,x:Ga(t[0],e[0])},{i:a-2,x:Ga(t[1],e[1])})}else 1===e[0]&&1===e[1]||r.push(hi(r)+"scale("+e+")")}(e.scale,r.scale,n,a),e=r=null,function(t){for(var e,r=-1,i=a.length;++r<i;)n[(e=a[r]).i]=e.x(t);return n.join("")}}function yi(t,e){return e=(e-=t=+t)||1/e,function(r){return(r-t)/e}}function vi(t,e){return e=(e-=t=+t)||1/e,function(r){return Math.max(0,Math.min(1,(r-t)/e))}}function mi(t){for(var e=t.source,r=t.target,n=function(t,e){if(t===e)return t;var r=xi(t),n=xi(e),a=r.pop(),i=n.pop(),o=null;for(;a===i;)o=a,a=r.pop(),i=n.pop();return o}(e,r),a=[e];e!==n;)e=e.parent,a.push(e);for(var i=a.length;r!==n;)a.splice(i,0,r),r=r.parent;return a}function xi(t){for(var e=[],r=t.parent;null!=r;)e.push(t),t=r,r=r.parent;return e.push(t),e}function bi(t){t.fixed|=2}function _i(t){t.fixed&=-7}function wi(t){t.fixed|=4,t.px=t.x,t.py=t.y}function ki(t){t.fixed&=-5}t.interpolateTransform=gi,t.layout={},t.layout.bundle=function(){return function(t){for(var e=[],r=-1,n=t.length;++r<n;)e.push(mi(t[r]));return e}},t.layout.chord=function(){var e,r,n,a,i,o,l,s={},c=0;function u(){var s,u,d,p,h,g={},y=[],v=t.range(a),m=[];for(e=[],r=[],s=0,p=-1;++p<a;){for(u=0,h=-1;++h<a;)u+=n[p][h];y.push(u),m.push(t.range(a)),s+=u}for(i&&v.sort(function(t,e){return i(y[t],y[e])}),o&&m.forEach(function(t,e){t.sort(function(t,r){return o(n[e][t],n[e][r])})}),s=(At-c*a)/s,u=0,p=-1;++p<a;){for(d=u,h=-1;++h<a;){var x=v[p],b=m[x][h],_=n[x][b],w=u,k=u+=_*s;g[x+"-"+b]={index:x,subindex:b,startAngle:w,endAngle:k,value:_}}r[x]={index:x,startAngle:d,endAngle:u,value:y[x]},u+=c}for(p=-1;++p<a;)for(h=p-1;++h<a;){var M=g[p+"-"+h],T=g[h+"-"+p];(M.value||T.value)&&e.push(M.value<T.value?{source:T,target:M}:{source:M,target:T})}l&&f()}function f(){e.sort(function(t,e){return l((t.source.value+t.target.value)/2,(e.source.value+e.target.value)/2)})}return s.matrix=function(t){return arguments.length?(a=(n=t)&&n.length,e=r=null,s):n},s.padding=function(t){return arguments.length?(c=t,e=r=null,s):c},s.sortGroups=function(t){return arguments.length?(i=t,e=r=null,s):i},s.sortSubgroups=function(t){return arguments.length?(o=t,e=null,s):o},s.sortChords=function(t){return arguments.length?(l=t,e&&f(),s):l},s.chords=function(){return e||u(),e},s.groups=function(){return r||u(),r},s},t.layout.force=function(){var e,r,n,a,i,o,l={},s=t.dispatch("start","tick","end"),c=[1,1],u=.9,f=Mi,d=Ti,p=-30,h=Ai,g=.1,y=.64,v=[],m=[];function x(t){return function(e,r,n,a){if(e.point!==t){var i=e.cx-t.x,o=e.cy-t.y,l=a-r,s=i*i+o*o;if(l*l/y<s){if(s<h){var c=e.charge/s;t.px-=i*c,t.py-=o*c}return!0}if(e.point&&s&&s<h){c=e.pointCharge/s;t.px-=i*c,t.py-=o*c}}return!e.charge}}function b(e){e.px=t.event.x,e.py=t.event.y,l.resume()}return l.tick=function(){if((n*=.99)<.005)return e=null,s.end({type:"end",alpha:n=0}),!0;var r,l,f,d,h,y,b,_,w,k=v.length,M=m.length;for(l=0;l<M;++l)d=(f=m[l]).source,(y=(_=(h=f.target).x-d.x)*_+(w=h.y-d.y)*w)&&(_*=y=n*i[l]*((y=Math.sqrt(y))-a[l])/y,w*=y,h.x-=_*(b=d.weight+h.weight?d.weight/(d.weight+h.weight):.5),h.y-=w*b,d.x+=_*(b=1-b),d.y+=w*b);if((b=n*g)&&(_=c[0]/2,w=c[1]/2,l=-1,b))for(;++l<k;)(f=v[l]).x+=(_-f.x)*b,f.y+=(w-f.y)*b;if(p)for(!function t(e,r,n){var a=0,i=0;e.charge=0;if(!e.leaf)for(var o,l=e.nodes,s=l.length,c=-1;++c<s;)null!=(o=l[c])&&(t(o,r,n),e.charge+=o.charge,a+=o.charge*o.cx,i+=o.charge*o.cy);if(e.point){e.leaf||(e.point.x+=Math.random()-.5,e.point.y+=Math.random()-.5);var u=r*n[e.point.index];e.charge+=e.pointCharge=u,a+=u*e.point.x,i+=u*e.point.y}e.cx=a/e.charge;e.cy=i/e.charge}(r=t.geom.quadtree(v),n,o),l=-1;++l<k;)(f=v[l]).fixed||r.visit(x(f));for(l=-1;++l<k;)(f=v[l]).fixed?(f.x=f.px,f.y=f.py):(f.x-=(f.px-(f.px=f.x))*u,f.y-=(f.py-(f.py=f.y))*u);s.tick({type:"tick",alpha:n})},l.nodes=function(t){return arguments.length?(v=t,l):v},l.links=function(t){return arguments.length?(m=t,l):m},l.size=function(t){return arguments.length?(c=t,l):c},l.linkDistance=function(t){return arguments.length?(f="function"==typeof t?t:+t,l):f},l.distance=l.linkDistance,l.linkStrength=function(t){return arguments.length?(d="function"==typeof t?t:+t,l):d},l.friction=function(t){return arguments.length?(u=+t,l):u},l.charge=function(t){return arguments.length?(p="function"==typeof t?t:+t,l):p},l.chargeDistance=function(t){return arguments.length?(h=t*t,l):Math.sqrt(h)},l.gravity=function(t){return arguments.length?(g=+t,l):g},l.theta=function(t){return arguments.length?(y=t*t,l):Math.sqrt(y)},l.alpha=function(t){return arguments.length?(t=+t,n?t>0?n=t:(e.c=null,e.t=NaN,e=null,s.end({type:"end",alpha:n=0})):t>0&&(s.start({type:"start",alpha:n=t}),e=Me(l.tick)),l):n},l.start=function(){var t,e,r,n=v.length,s=m.length,u=c[0],h=c[1];for(t=0;t<n;++t)(r=v[t]).index=t,r.weight=0;for(t=0;t<s;++t)"number"==typeof(r=m[t]).source&&(r.source=v[r.source]),"number"==typeof r.target&&(r.target=v[r.target]),++r.source.weight,++r.target.weight;for(t=0;t<n;++t)r=v[t],isNaN(r.x)&&(r.x=g("x",u)),isNaN(r.y)&&(r.y=g("y",h)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(a=[],"function"==typeof f)for(t=0;t<s;++t)a[t]=+f.call(this,m[t],t);else for(t=0;t<s;++t)a[t]=f;if(i=[],"function"==typeof d)for(t=0;t<s;++t)i[t]=+d.call(this,m[t],t);else for(t=0;t<s;++t)i[t]=d;if(o=[],"function"==typeof p)for(t=0;t<n;++t)o[t]=+p.call(this,v[t],t);else for(t=0;t<n;++t)o[t]=p;function g(r,a){if(!e){for(e=new Array(n),c=0;c<n;++c)e[c]=[];for(c=0;c<s;++c){var i=m[c];e[i.source.index].push(i.target),e[i.target.index].push(i.source)}}for(var o,l=e[t],c=-1,u=l.length;++c<u;)if(!isNaN(o=l[c][r]))return o;return Math.random()*a}return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){if(r||(r=t.behavior.drag().origin(P).on("dragstart.force",bi).on("drag.force",b).on("dragend.force",_i)),!arguments.length)return r;this.on("mouseover.force",wi).on("mouseout.force",ki).call(r)},t.rebind(l,s,"on")};var Mi=20,Ti=1,Ai=1/0;function Li(e,r){return t.rebind(e,r,"sort","children","value"),e.nodes=e,e.links=zi,e}function Ci(t,e){for(var r=[t];null!=(t=r.pop());)if(e(t),(a=t.children)&&(n=a.length))for(var n,a;--n>=0;)r.push(a[n])}function Si(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(i=t.children)&&(a=i.length))for(var a,i,o=-1;++o<a;)r.push(i[o]);for(;null!=(t=n.pop());)e(t)}function Oi(t){return t.children}function Pi(t){return t.value}function Di(t,e){return e.value-t.value}function zi(e){return t.merge(e.map(function(t){return(t.children||[]).map(function(e){return{source:t,target:e}})}))}t.layout.hierarchy=function(){var t=Di,e=Oi,r=Pi;function n(a){var i,o=[a],l=[];for(a.depth=0;null!=(i=o.pop());)if(l.push(i),(c=e.call(n,i,i.depth))&&(s=c.length)){for(var s,c,u;--s>=0;)o.push(u=c[s]),u.parent=i,u.depth=i.depth+1;r&&(i.value=0),i.children=c}else r&&(i.value=+r.call(n,i,i.depth)||0),delete i.children;return Si(a,function(e){var n,a;t&&(n=e.children)&&n.sort(t),r&&(a=e.parent)&&(a.value+=e.value)}),l}return n.sort=function(e){return arguments.length?(t=e,n):t},n.children=function(t){return arguments.length?(e=t,n):e},n.value=function(t){return arguments.length?(r=t,n):r},n.revalue=function(t){return r&&(Ci(t,function(t){t.children&&(t.value=0)}),Si(t,function(t){var e;t.children||(t.value=+r.call(n,t,t.depth)||0),(e=t.parent)&&(e.value+=t.value)})),t},n},t.layout.partition=function(){var e=t.layout.hierarchy(),r=[1,1];function n(t,n){var a=e.call(this,t,n);return function t(e,r,n,a){var i=e.children;if(e.x=r,e.y=e.depth*a,e.dx=n,e.dy=a,i&&(o=i.length)){var o,l,s,c=-1;for(n=e.value?n/e.value:0;++c<o;)t(l=i[c],r,s=l.value*n,a),r+=s}}(a[0],0,r[0],r[1]/function t(e){var r=e.children,n=0;if(r&&(a=r.length))for(var a,i=-1;++i<a;)n=Math.max(n,t(r[i]));return 1+n}(a[0])),a}return n.size=function(t){return arguments.length?(r=t,n):r},Li(n,e)},t.layout.pie=function(){var e=Number,r=Ei,n=0,a=At,i=0;function o(l){var s,c=l.length,u=l.map(function(t,r){return+e.call(o,t,r)}),f=+("function"==typeof n?n.apply(this,arguments):n),d=("function"==typeof a?a.apply(this,arguments):a)-f,p=Math.min(Math.abs(d)/c,+("function"==typeof i?i.apply(this,arguments):i)),h=p*(d<0?-1:1),g=t.sum(u),y=g?(d-c*h)/g:0,v=t.range(c),m=[];return null!=r&&v.sort(r===Ei?function(t,e){return u[e]-u[t]}:function(t,e){return r(l[t],l[e])}),v.forEach(function(t){m[t]={data:l[t],value:s=u[t],startAngle:f,endAngle:f+=s*y+h,padAngle:p}}),m}return o.value=function(t){return arguments.length?(e=t,o):e},o.sort=function(t){return arguments.length?(r=t,o):r},o.startAngle=function(t){return arguments.length?(n=t,o):n},o.endAngle=function(t){return arguments.length?(a=t,o):a},o.padAngle=function(t){return arguments.length?(i=t,o):i},o};var Ei={};function Ii(t){return t.x}function Ni(t){return t.y}function Ri(t,e,r){t.y0=e,t.y=r}t.layout.stack=function(){var e=P,r=Bi,n=Hi,a=Ri,i=Ii,o=Ni;function l(s,c){if(!(p=s.length))return s;var u=s.map(function(t,r){return e.call(l,t,r)}),f=u.map(function(t){return t.map(function(t,e){return[i.call(l,t,e),o.call(l,t,e)]})}),d=r.call(l,f,c);u=t.permute(u,d),f=t.permute(f,d);var p,h,g,y,v=n.call(l,f,c),m=u[0].length;for(g=0;g<m;++g)for(a.call(l,u[0][g],y=v[g],f[0][g][1]),h=1;h<p;++h)a.call(l,u[h][g],y+=f[h-1][g][1],f[h][g][1]);return s}return l.values=function(t){return arguments.length?(e=t,l):e},l.order=function(t){return arguments.length?(r="function"==typeof t?t:Fi.get(t)||Bi,l):r},l.offset=function(t){return arguments.length?(n="function"==typeof t?t:ji.get(t)||Hi,l):n},l.x=function(t){return arguments.length?(i=t,l):i},l.y=function(t){return arguments.length?(o=t,l):o},l.out=function(t){return arguments.length?(a=t,l):a},l};var Fi=t.map({"inside-out":function(e){var r,n,a=e.length,i=e.map(qi),o=e.map(Vi),l=t.range(a).sort(function(t,e){return i[t]-i[e]}),s=0,c=0,u=[],f=[];for(r=0;r<a;++r)n=l[r],s<c?(s+=o[n],u.push(n)):(c+=o[n],f.push(n));return f.reverse().concat(u)},reverse:function(e){return t.range(e.length).reverse()},default:Bi}),ji=t.map({silhouette:function(t){var e,r,n,a=t.length,i=t[0].length,o=[],l=0,s=[];for(r=0;r<i;++r){for(e=0,n=0;e<a;e++)n+=t[e][r][1];n>l&&(l=n),o.push(n)}for(r=0;r<i;++r)s[r]=(l-o[r])/2;return s},wiggle:function(t){var e,r,n,a,i,o,l,s,c,u=t.length,f=t[0],d=f.length,p=[];for(p[0]=s=c=0,r=1;r<d;++r){for(e=0,a=0;e<u;++e)a+=t[e][r][1];for(e=0,i=0,l=f[r][0]-f[r-1][0];e<u;++e){for(n=0,o=(t[e][r][1]-t[e][r-1][1])/(2*l);n<e;++n)o+=(t[n][r][1]-t[n][r-1][1])/l;i+=o*t[e][r][1]}p[r]=s-=a?i/a*l:0,s<c&&(c=s)}for(r=0;r<d;++r)p[r]-=c;return p},expand:function(t){var e,r,n,a=t.length,i=t[0].length,o=1/a,l=[];for(r=0;r<i;++r){for(e=0,n=0;e<a;e++)n+=t[e][r][1];if(n)for(e=0;e<a;e++)t[e][r][1]/=n;else for(e=0;e<a;e++)t[e][r][1]=o}for(r=0;r<i;++r)l[r]=0;return l},zero:Hi});function Bi(e){return t.range(e.length)}function Hi(t){for(var e=-1,r=t[0].length,n=[];++e<r;)n[e]=0;return n}function qi(t){for(var e,r=1,n=0,a=t[0][1],i=t.length;r<i;++r)(e=t[r][1])>a&&(n=r,a=e);return n}function Vi(t){return t.reduce(Ui,0)}function Ui(t,e){return t+e[1]}function Gi(t,e){return Yi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function Yi(t,e){for(var r=-1,n=+t[0],a=(t[1]-n)/e,i=[];++r<=e;)i[r]=a*r+n;return i}function Xi(e){return[t.min(e),t.max(e)]}function Zi(t,e){return t.value-e.value}function Wi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Qi(t,e){t._pack_next=e,e._pack_prev=t}function Ji(t,e){var r=e.x-t.x,n=e.y-t.y,a=t.r+e.r;return.999*a*a>r*r+n*n}function $i(t){if((e=t.children)&&(s=e.length)){var e,r,n,a,i,o,l,s,c=1/0,u=-1/0,f=1/0,d=-1/0;if(e.forEach(Ki),(r=e[0]).x=-r.r,r.y=0,x(r),s>1&&((n=e[1]).x=n.r,n.y=0,x(n),s>2))for(eo(r,n,a=e[2]),x(a),Wi(r,a),r._pack_prev=a,Wi(a,n),n=r._pack_next,i=3;i<s;i++){eo(r,n,a=e[i]);var p=0,h=1,g=1;for(o=n._pack_next;o!==n;o=o._pack_next,h++)if(Ji(o,a)){p=1;break}if(1==p)for(l=r._pack_prev;l!==o._pack_prev&&!Ji(l,a);l=l._pack_prev,g++);p?(h<g||h==g&&n.r<r.r?Qi(r,n=o):Qi(r=l,n),i--):(Wi(r,a),n=a,x(a))}var y=(c+u)/2,v=(f+d)/2,m=0;for(i=0;i<s;i++)(a=e[i]).x-=y,a.y-=v,m=Math.max(m,a.r+Math.sqrt(a.x*a.x+a.y*a.y));t.r=m,e.forEach(to)}function x(t){c=Math.min(t.x-t.r,c),u=Math.max(t.x+t.r,u),f=Math.min(t.y-t.r,f),d=Math.max(t.y+t.r,d)}}function Ki(t){t._pack_next=t._pack_prev=t}function to(t){delete t._pack_next,delete t._pack_prev}function eo(t,e,r){var n=t.r+r.r,a=e.x-t.x,i=e.y-t.y;if(n&&(a||i)){var o=e.r+r.r,l=a*a+i*i,s=.5+((n*=n)-(o*=o))/(2*l),c=Math.sqrt(Math.max(0,2*o*(n+l)-(n-=l)*n-o*o))/(2*l);r.x=t.x+s*a+c*i,r.y=t.y+s*i-c*a}else r.x=t.x+n,r.y=t.y}function ro(t,e){return t.parent==e.parent?1:2}function no(t){var e=t.children;return e.length?e[0]:t.t}function ao(t){var e,r=t.children;return(e=r.length)?r[e-1]:t.t}function io(t,e,r){var n=r/(e.i-t.i);e.c-=n,e.s+=r,t.c+=n,e.z+=r,e.m+=r}function oo(t,e,r){return t.a.parent===e.parent?t.a:r}function lo(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function so(t,e){var r=t.x+e[3],n=t.y+e[0],a=t.dx-e[1]-e[3],i=t.dy-e[0]-e[2];return a<0&&(r+=a/2,a=0),i<0&&(n+=i/2,i=0),{x:r,y:n,dx:a,dy:i}}function co(t){var e=t[0],r=t[t.length-1];return e<r?[e,r]:[r,e]}function uo(t){return t.rangeExtent?t.rangeExtent():co(t.range())}function fo(t,e,r,n){var a=r(t[0],t[1]),i=n(e[0],e[1]);return function(t){return i(a(t))}}function po(t,e){var r,n=0,a=t.length-1,i=t[n],o=t[a];return o<i&&(r=n,n=a,a=r,r=i,i=o,o=r),t[n]=e.floor(i),t[a]=e.ceil(o),t}function ho(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:go}t.layout.histogram=function(){var e=!0,r=Number,n=Xi,a=Gi;function i(i,o){for(var l,s,c=[],u=i.map(r,this),f=n.call(this,u,o),d=a.call(this,f,u,o),p=(o=-1,u.length),h=d.length-1,g=e?1:1/p;++o<h;)(l=c[o]=[]).dx=d[o+1]-(l.x=d[o]),l.y=0;if(h>0)for(o=-1;++o<p;)(s=u[o])>=f[0]&&s<=f[1]&&((l=c[t.bisect(d,s,1,h)-1]).y+=g,l.push(i[o]));return c}return i.value=function(t){return arguments.length?(r=t,i):r},i.range=function(t){return arguments.length?(n=ye(t),i):n},i.bins=function(t){return arguments.length?(a="number"==typeof t?function(e){return Yi(e,t)}:ye(t),i):a},i.frequency=function(t){return arguments.length?(e=!!t,i):e},i},t.layout.pack=function(){var e,r=t.layout.hierarchy().sort(Zi),n=0,a=[1,1];function i(t,i){var o=r.call(this,t,i),l=o[0],s=a[0],c=a[1],u=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(l.x=l.y=0,Si(l,function(t){t.r=+u(t.value)}),Si(l,$i),n){var f=n*(e?1:Math.max(2*l.r/s,2*l.r/c))/2;Si(l,function(t){t.r+=f}),Si(l,$i),Si(l,function(t){t.r-=f})}return function t(e,r,n,a){var i=e.children;e.x=r+=a*e.x;e.y=n+=a*e.y;e.r*=a;if(i)for(var o=-1,l=i.length;++o<l;)t(i[o],r,n,a)}(l,s/2,c/2,e?1:1/Math.max(2*l.r/s,2*l.r/c)),o}return i.size=function(t){return arguments.length?(a=t,i):a},i.radius=function(t){return arguments.length?(e=null==t||"function"==typeof t?t:+t,i):e},i.padding=function(t){return arguments.length?(n=+t,i):n},Li(i,r)},t.layout.tree=function(){var e=t.layout.hierarchy().sort(null).value(null),r=ro,n=[1,1],a=null;function i(t,i){var c=e.call(this,t,i),u=c[0],f=function(t){var e,r={A:null,children:[t]},n=[r];for(;null!=(e=n.pop());)for(var a,i=e.children,o=0,l=i.length;o<l;++o)n.push((i[o]=a={_:i[o],parent:e,children:(a=i[o].children)&&a.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=a);return r.children[0]}(u);if(Si(f,o),f.parent.m=-f.z,Ci(f,l),a)Ci(u,s);else{var d=u,p=u,h=u;Ci(u,function(t){t.x<d.x&&(d=t),t.x>p.x&&(p=t),t.depth>h.depth&&(h=t)});var g=r(d,p)/2-d.x,y=n[0]/(p.x+r(p,d)/2+g),v=n[1]/(h.depth||1);Ci(u,function(t){t.x=(t.x+g)*y,t.y=t.depth*v})}return c}function o(t){var e=t.children,n=t.parent.children,a=t.i?n[t.i-1]:null;if(e.length){!function(t){var e,r=0,n=0,a=t.children,i=a.length;for(;--i>=0;)(e=a[i]).z+=r,e.m+=r,r+=e.s+(n+=e.c)}(t);var i=(e[0].z+e[e.length-1].z)/2;a?(t.z=a.z+r(t._,a._),t.m=t.z-i):t.z=i}else a&&(t.z=a.z+r(t._,a._));t.parent.A=function(t,e,n){if(e){for(var a,i=t,o=t,l=e,s=i.parent.children[0],c=i.m,u=o.m,f=l.m,d=s.m;l=ao(l),i=no(i),l&&i;)s=no(s),(o=ao(o)).a=t,(a=l.z+f-i.z-c+r(l._,i._))>0&&(io(oo(l,t,n),t,a),c+=a,u+=a),f+=l.m,c+=i.m,d+=s.m,u+=o.m;l&&!ao(o)&&(o.t=l,o.m+=f-u),i&&!no(s)&&(s.t=i,s.m+=c-d,n=t)}return n}(t,a,t.parent.A||n[0])}function l(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function s(t){t.x*=n[0],t.y=t.depth*n[1]}return i.separation=function(t){return arguments.length?(r=t,i):r},i.size=function(t){return arguments.length?(a=null==(n=t)?s:null,i):a?null:n},i.nodeSize=function(t){return arguments.length?(a=null==(n=t)?null:s,i):a?n:null},Li(i,e)},t.layout.cluster=function(){var e=t.layout.hierarchy().sort(null).value(null),r=ro,n=[1,1],a=!1;function i(i,o){var l,s=e.call(this,i,o),c=s[0],u=0;Si(c,function(e){var n=e.children;n&&n.length?(e.x=function(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}(n),e.y=function(e){return 1+t.max(e,function(t){return t.y})}(n)):(e.x=l?u+=r(e,l):0,e.y=0,l=e)});var f=function t(e){var r=e.children;return r&&r.length?t(r[0]):e}(c),d=function t(e){var r,n=e.children;return n&&(r=n.length)?t(n[r-1]):e}(c),p=f.x-r(f,d)/2,h=d.x+r(d,f)/2;return Si(c,a?function(t){t.x=(t.x-c.x)*n[0],t.y=(c.y-t.y)*n[1]}:function(t){t.x=(t.x-p)/(h-p)*n[0],t.y=(1-(c.y?t.y/c.y:1))*n[1]}),s}return i.separation=function(t){return arguments.length?(r=t,i):r},i.size=function(t){return arguments.length?(a=null==(n=t),i):a?null:n},i.nodeSize=function(t){return arguments.length?(a=null!=(n=t),i):a?n:null},Li(i,e)},t.layout.treemap=function(){var e,r=t.layout.hierarchy(),n=Math.round,a=[1,1],i=null,o=lo,l=!1,s="squarify",c=.5*(1+Math.sqrt(5));function u(t,e){for(var r,n,a=-1,i=t.length;++a<i;)n=(r=t[a]).value*(e<0?0:e),r.area=isNaN(n)||n<=0?0:n}function f(t){var e=t.children;if(e&&e.length){var r,n,a,i=o(t),l=[],c=e.slice(),d=1/0,g="slice"===s?i.dx:"dice"===s?i.dy:"slice-dice"===s?1&t.depth?i.dy:i.dx:Math.min(i.dx,i.dy);for(u(c,i.dx*i.dy/t.value),l.area=0;(a=c.length)>0;)l.push(r=c[a-1]),l.area+=r.area,"squarify"!==s||(n=p(l,g))<=d?(c.pop(),d=n):(l.area-=l.pop().area,h(l,g,i,!1),g=Math.min(i.dx,i.dy),l.length=l.area=0,d=1/0);l.length&&(h(l,g,i,!0),l.length=l.area=0),e.forEach(f)}}function d(t){var e=t.children;if(e&&e.length){var r,n=o(t),a=e.slice(),i=[];for(u(a,n.dx*n.dy/t.value),i.area=0;r=a.pop();)i.push(r),i.area+=r.area,null!=r.z&&(h(i,r.z?n.dx:n.dy,n,!a.length),i.length=i.area=0);e.forEach(d)}}function p(t,e){for(var r,n=t.area,a=0,i=1/0,o=-1,l=t.length;++o<l;)(r=t[o].area)&&(r<i&&(i=r),r>a&&(a=r));return e*=e,(n*=n)?Math.max(e*a*c/n,n/(e*i*c)):1/0}function h(t,e,r,a){var i,o=-1,l=t.length,s=r.x,c=r.y,u=e?n(t.area/e):0;if(e==r.dx){for((a||u>r.dy)&&(u=r.dy);++o<l;)(i=t[o]).x=s,i.y=c,i.dy=u,s+=i.dx=Math.min(r.x+r.dx-s,u?n(i.area/u):0);i.z=!0,i.dx+=r.x+r.dx-s,r.y+=u,r.dy-=u}else{for((a||u>r.dx)&&(u=r.dx);++o<l;)(i=t[o]).x=s,i.y=c,i.dx=u,c+=i.dy=Math.min(r.y+r.dy-c,u?n(i.area/u):0);i.z=!1,i.dy+=r.y+r.dy-c,r.x+=u,r.dx-=u}}function g(t){var n=e||r(t),i=n[0];return i.x=i.y=0,i.value?(i.dx=a[0],i.dy=a[1]):i.dx=i.dy=0,e&&r.revalue(i),u([i],i.dx*i.dy/i.value),(e?d:f)(i),l&&(e=n),n}return g.size=function(t){return arguments.length?(a=t,g):a},g.padding=function(t){if(!arguments.length)return i;function e(e){return so(e,t)}var r;return o=null==(i=t)?lo:"function"==(r=typeof t)?function(e){var r=t.call(g,e,e.depth);return null==r?lo(e):so(e,"number"==typeof r?[r,r,r,r]:r)}:"number"===r?(t=[t,t,t,t],e):e,g},g.round=function(t){return arguments.length?(n=t?Math.round:Number,g):n!=Number},g.sticky=function(t){return arguments.length?(l=t,e=null,g):l},g.ratio=function(t){return arguments.length?(c=t,g):c},g.mode=function(t){return arguments.length?(s=t+"",g):s},Li(g,r)},t.random={normal:function(t,e){var r=arguments.length;return r<2&&(e=1),r<1&&(t=0),function(){var r,n,a;do{a=(r=2*Math.random()-1)*r+(n=2*Math.random()-1)*n}while(!a||a>1);return t+e*r*Math.sqrt(-2*Math.log(a)/a)}},logNormal:function(){var e=t.random.normal.apply(t,arguments);return function(){return Math.exp(e())}},bates:function(e){var r=t.random.irwinHall(e);return function(){return r()/e}},irwinHall:function(t){return function(){for(var e=0,r=0;r<t;r++)e+=Math.random();return e}}},t.scale={};var go={floor:P,ceil:P};function yo(e,r,n,a){var i=[],o=[],l=0,s=Math.min(e.length,r.length)-1;for(e[s]<e[0]&&(e=e.slice().reverse(),r=r.slice().reverse());++l<=s;)i.push(n(e[l-1],e[l])),o.push(a(r[l-1],r[l]));return function(r){var n=t.bisect(e,r,1,s)-1;return o[n](i[n](r))}}function vo(e,r){return t.rebind(e,r,"range","rangeRound","interpolate","clamp")}function mo(t,e){return po(t,ho(xo(t,e)[2])),po(t,ho(xo(t,e)[2])),t}function xo(t,e){null==e&&(e=10);var r=co(t),n=r[1]-r[0],a=Math.pow(10,Math.floor(Math.log(n/e)/Math.LN10)),i=e/n*a;return i<=.15?a*=10:i<=.35?a*=5:i<=.75&&(a*=2),r[0]=Math.ceil(r[0]/a)*a,r[1]=Math.floor(r[1]/a)*a+.5*a,r[2]=a,r}function bo(e,r){return t.range.apply(t,xo(e,r))}function _o(e,r,n){var a=xo(e,r);if(n){var i=Oe.exec(n);if(i.shift(),"s"===i[8]){var o=t.formatPrefix(Math.max(m(a[0]),m(a[1])));return i[7]||(i[7]="."+ko(o.scale(a[2]))),i[8]="f",n=t.format(i.join("")),function(t){return n(o.scale(t))+o.symbol}}i[7]||(i[7]="."+function(t,e){var r=ko(e[2]);return t in wo?Math.abs(r-ko(Math.max(m(e[0]),m(e[1]))))+ +("e"!==t):r-2*("%"===t)}(i[8],a)),n=i.join("")}else n=",."+ko(a[2])+"f";return t.format(n)}t.scale.linear=function(){return function t(e,r,n,a){var i,o;function l(){var t=Math.min(e.length,r.length)>2?yo:fo,l=a?vi:yi;return i=t(e,r,l,n),o=t(r,e,l,Wa),s}function s(t){return i(t)}s.invert=function(t){return o(t)};s.domain=function(t){return arguments.length?(e=t.map(Number),l()):e};s.range=function(t){return arguments.length?(r=t,l()):r};s.rangeRound=function(t){return s.range(t).interpolate(ci)};s.clamp=function(t){return arguments.length?(a=t,l()):a};s.interpolate=function(t){return arguments.length?(n=t,l()):n};s.ticks=function(t){return bo(e,t)};s.tickFormat=function(t,r){return _o(e,t,r)};s.nice=function(t){return mo(e,t),l()};s.copy=function(){return t(e,r,n,a)};return l()}([0,1],[0,1],Wa,!1)};var wo={s:1,g:1,p:1,r:1,e:1};function ko(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}t.scale.log=function(){return function e(r,n,a,i){function o(t){return(a?Math.log(t<0?0:t):-Math.log(t>0?0:-t))/Math.log(n)}function l(t){return a?Math.pow(n,t):-Math.pow(n,-t)}function s(t){return r(o(t))}s.invert=function(t){return l(r.invert(t))};s.domain=function(t){return arguments.length?(a=t[0]>=0,r.domain((i=t.map(Number)).map(o)),s):i};s.base=function(t){return arguments.length?(n=+t,r.domain(i.map(o)),s):n};s.nice=function(){var t=po(i.map(o),a?Math:To);return r.domain(t),i=t.map(l),s};s.ticks=function(){var t=co(i),e=[],r=t[0],s=t[1],c=Math.floor(o(r)),u=Math.ceil(o(s)),f=n%1?2:n;if(isFinite(u-c)){if(a){for(;c<u;c++)for(var d=1;d<f;d++)e.push(l(c)*d);e.push(l(c))}else for(e.push(l(c));c++<u;)for(var d=f-1;d>0;d--)e.push(l(c)*d);for(c=0;e[c]<r;c++);for(u=e.length;e[u-1]>s;u--);e=e.slice(c,u)}return e};s.tickFormat=function(e,r){if(!arguments.length)return Mo;arguments.length<2?r=Mo:"function"!=typeof r&&(r=t.format(r));var a=Math.max(1,n*e/s.ticks().length);return function(t){var e=t/l(Math.round(o(t)));return e*n<n-.5&&(e*=n),e<=a?r(t):""}};s.copy=function(){return e(r.copy(),n,a,i)};return vo(s,r)}(t.scale.linear().domain([0,1]),10,!0,[1,10])};var Mo=t.format(".0e"),To={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};function Ao(t){return function(e){return e<0?-Math.pow(-e,t):Math.pow(e,t)}}t.scale.pow=function(){return function t(e,r,n){var a=Ao(r),i=Ao(1/r);function o(t){return e(a(t))}o.invert=function(t){return i(e.invert(t))};o.domain=function(t){return arguments.length?(e.domain((n=t.map(Number)).map(a)),o):n};o.ticks=function(t){return bo(n,t)};o.tickFormat=function(t,e){return _o(n,t,e)};o.nice=function(t){return o.domain(mo(n,t))};o.exponent=function(t){return arguments.length?(a=Ao(r=t),i=Ao(1/r),e.domain(n.map(a)),o):r};o.copy=function(){return t(e.copy(),r,n)};return vo(o,e)}(t.scale.linear(),1,[0,1])},t.scale.sqrt=function(){return t.scale.pow().exponent(.5)},t.scale.ordinal=function(){return function e(r,n){var a,i,o;function l(t){return i[((a.get(t)||("range"===n.t?a.set(t,r.push(t)):NaN))-1)%i.length]}function s(e,n){return t.range(r.length).map(function(t){return e+n*t})}l.domain=function(t){if(!arguments.length)return r;r=[],a=new b;for(var e,i=-1,o=t.length;++i<o;)a.has(e=t[i])||a.set(e,r.push(e));return l[n.t].apply(l,n.a)};l.range=function(t){return arguments.length?(i=t,o=0,n={t:"range",a:arguments},l):i};l.rangePoints=function(t,e){arguments.length<2&&(e=0);var a=t[0],c=t[1],u=r.length<2?(a=(a+c)/2,0):(c-a)/(r.length-1+e);return i=s(a+u*e/2,u),o=0,n={t:"rangePoints",a:arguments},l};l.rangeRoundPoints=function(t,e){arguments.length<2&&(e=0);var a=t[0],c=t[1],u=r.length<2?(a=c=Math.round((a+c)/2),0):(c-a)/(r.length-1+e)|0;return i=s(a+Math.round(u*e/2+(c-a-(r.length-1+e)*u)/2),u),o=0,n={t:"rangeRoundPoints",a:arguments},l};l.rangeBands=function(t,e,a){arguments.length<2&&(e=0),arguments.length<3&&(a=e);var c=t[1]<t[0],u=t[c-0],f=t[1-c],d=(f-u)/(r.length-e+2*a);return i=s(u+d*a,d),c&&i.reverse(),o=d*(1-e),n={t:"rangeBands",a:arguments},l};l.rangeRoundBands=function(t,e,a){arguments.length<2&&(e=0),arguments.length<3&&(a=e);var c=t[1]<t[0],u=t[c-0],f=t[1-c],d=Math.floor((f-u)/(r.length-e+2*a));return i=s(u+Math.round((f-u-(r.length-e)*d)/2),d),c&&i.reverse(),o=Math.round(d*(1-e)),n={t:"rangeRoundBands",a:arguments},l};l.rangeBand=function(){return o};l.rangeExtent=function(){return co(n.a[0])};l.copy=function(){return e(r,n)};return l.domain(r)}([],{t:"range",a:[[]]})},t.scale.category10=function(){return t.scale.ordinal().range(Lo)},t.scale.category20=function(){return t.scale.ordinal().range(Co)},t.scale.category20b=function(){return t.scale.ordinal().range(So)},t.scale.category20c=function(){return t.scale.ordinal().range(Oo)};var Lo=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(le),Co=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(le),So=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(le),Oo=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(le);function Po(){return 0}t.scale.quantile=function(){return function e(r,n){var a;function i(){var e=0,i=n.length;for(a=[];++e<i;)a[e-1]=t.quantile(r,e/i);return o}function o(e){if(!isNaN(e=+e))return n[t.bisect(a,e)]}o.domain=function(t){return arguments.length?(r=t.map(p).filter(h).sort(d),i()):r};o.range=function(t){return arguments.length?(n=t,i()):n};o.quantiles=function(){return a};o.invertExtent=function(t){return(t=n.indexOf(t))<0?[NaN,NaN]:[t>0?a[t-1]:r[0],t<a.length?a[t]:r[r.length-1]]};o.copy=function(){return e(r,n)};return i()}([],[])},t.scale.quantize=function(){return function t(e,r,n){var a,i;function o(t){return n[Math.max(0,Math.min(i,Math.floor(a*(t-e))))]}function l(){return a=n.length/(r-e),i=n.length-1,o}o.domain=function(t){return arguments.length?(e=+t[0],r=+t[t.length-1],l()):[e,r]};o.range=function(t){return arguments.length?(n=t,l()):n};o.invertExtent=function(t){return[t=(t=n.indexOf(t))<0?NaN:t/a+e,t+1/a]};o.copy=function(){return t(e,r,n)};return l()}(0,1,[0,1])},t.scale.threshold=function(){return function e(r,n){function a(e){if(e<=e)return n[t.bisect(r,e)]}a.domain=function(t){return arguments.length?(r=t,a):r};a.range=function(t){return arguments.length?(n=t,a):n};a.invertExtent=function(t){return t=n.indexOf(t),[r[t-1],r[t]]};a.copy=function(){return e(r,n)};return a}([.5],[0,1])},t.scale.identity=function(){return function t(e){function r(t){return+t}r.invert=r;r.domain=r.range=function(t){return arguments.length?(e=t.map(r),r):e};r.ticks=function(t){return bo(e,t)};r.tickFormat=function(t,r){return _o(e,t,r)};r.copy=function(){return t(e)};return r}([0,1])},t.svg={},t.svg.arc=function(){var t=zo,e=Eo,r=Po,n=Do,a=Io,i=No,o=Ro;function l(){var l=Math.max(0,+t.apply(this,arguments)),c=Math.max(0,+e.apply(this,arguments)),u=a.apply(this,arguments)-Ct,f=i.apply(this,arguments)-Ct,d=Math.abs(f-u),p=u>f?0:1;if(c<l&&(h=c,c=l,l=h),d>=Lt)return s(c,p)+(l?s(l,1-p):"")+"Z";var h,g,y,v,m,x,b,_,w,k,M,T,A=0,L=0,C=[];if((v=(+o.apply(this,arguments)||0)/2)&&(y=n===Do?Math.sqrt(l*l+c*c):+n.apply(this,arguments),p||(L*=-1),c&&(L=Et(y/c*Math.sin(v))),l&&(A=Et(y/l*Math.sin(v)))),c){m=c*Math.cos(u+L),x=c*Math.sin(u+L),b=c*Math.cos(f-L),_=c*Math.sin(f-L);var S=Math.abs(f-u-2*L)<=Tt?0:1;if(L&&Fo(m,x,b,_)===p^S){var O=(u+f)/2;m=c*Math.cos(O),x=c*Math.sin(O),b=_=null}}else m=x=0;if(l){w=l*Math.cos(f-A),k=l*Math.sin(f-A),M=l*Math.cos(u+A),T=l*Math.sin(u+A);var P=Math.abs(u-f+2*A)<=Tt?0:1;if(A&&Fo(w,k,M,T)===1-p^P){var D=(u+f)/2;w=l*Math.cos(D),k=l*Math.sin(D),M=T=null}}else w=k=0;if(d>kt&&(h=Math.min(Math.abs(c-l)/2,+r.apply(this,arguments)))>.001){g=l<c^p?0:1;var z=h,E=h;if(d<Tt){var I=null==M?[w,k]:null==b?[m,x]:la([m,x],[M,T],[b,_],[w,k]),N=m-I[0],R=x-I[1],F=b-I[0],j=_-I[1],B=1/Math.sin(Math.acos((N*F+R*j)/(Math.sqrt(N*N+R*R)*Math.sqrt(F*F+j*j)))/2),H=Math.sqrt(I[0]*I[0]+I[1]*I[1]);E=Math.min(h,(l-H)/(B-1)),z=Math.min(h,(c-H)/(B+1))}if(null!=b){var q=jo(null==M?[w,k]:[M,T],[m,x],c,z,p),V=jo([b,_],[w,k],c,z,p);h===z?C.push("M",q[0],"A",z,",",z," 0 0,",g," ",q[1],"A",c,",",c," 0 ",1-p^Fo(q[1][0],q[1][1],V[1][0],V[1][1]),",",p," ",V[1],"A",z,",",z," 0 0,",g," ",V[0]):C.push("M",q[0],"A",z,",",z," 0 1,",g," ",V[0])}else C.push("M",m,",",x);if(null!=M){var U=jo([m,x],[M,T],l,-E,p),G=jo([w,k],null==b?[m,x]:[b,_],l,-E,p);h===E?C.push("L",G[0],"A",E,",",E," 0 0,",g," ",G[1],"A",l,",",l," 0 ",p^Fo(G[1][0],G[1][1],U[1][0],U[1][1]),",",1-p," ",U[1],"A",E,",",E," 0 0,",g," ",U[0]):C.push("L",G[0],"A",E,",",E," 0 0,",g," ",U[0])}else C.push("L",w,",",k)}else C.push("M",m,",",x),null!=b&&C.push("A",c,",",c," 0 ",S,",",p," ",b,",",_),C.push("L",w,",",k),null!=M&&C.push("A",l,",",l," 0 ",P,",",1-p," ",M,",",T);return C.push("Z"),C.join("")}function s(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}return l.innerRadius=function(e){return arguments.length?(t=ye(e),l):t},l.outerRadius=function(t){return arguments.length?(e=ye(t),l):e},l.cornerRadius=function(t){return arguments.length?(r=ye(t),l):r},l.padRadius=function(t){return arguments.length?(n=t==Do?Do:ye(t),l):n},l.startAngle=function(t){return arguments.length?(a=ye(t),l):a},l.endAngle=function(t){return arguments.length?(i=ye(t),l):i},l.padAngle=function(t){return arguments.length?(o=ye(t),l):o},l.centroid=function(){var r=(+t.apply(this,arguments)+ +e.apply(this,arguments))/2,n=(+a.apply(this,arguments)+ +i.apply(this,arguments))/2-Ct;return[Math.cos(n)*r,Math.sin(n)*r]},l};var Do="auto";function zo(t){return t.innerRadius}function Eo(t){return t.outerRadius}function Io(t){return t.startAngle}function No(t){return t.endAngle}function Ro(t){return t&&t.padAngle}function Fo(t,e,r,n){return(t-r)*e-(e-n)*t>0?0:1}function jo(t,e,r,n,a){var i=t[0]-e[0],o=t[1]-e[1],l=(a?n:-n)/Math.sqrt(i*i+o*o),s=l*o,c=-l*i,u=t[0]+s,f=t[1]+c,d=e[0]+s,p=e[1]+c,h=(u+d)/2,g=(f+p)/2,y=d-u,v=p-f,m=y*y+v*v,x=r-n,b=u*p-d*f,_=(v<0?-1:1)*Math.sqrt(Math.max(0,x*x*m-b*b)),w=(b*v-y*_)/m,k=(-b*y-v*_)/m,M=(b*v+y*_)/m,T=(-b*y+v*_)/m,A=w-h,L=k-g,C=M-h,S=T-g;return A*A+L*L>C*C+S*S&&(w=M,k=T),[[w-s,k-c],[w*r/x,k*r/x]]}function Bo(t){var e=ea,r=ra,n=Yr,a=qo,i=a.key,o=.7;function l(i){var l,s=[],c=[],u=-1,f=i.length,d=ye(e),p=ye(r);function h(){s.push("M",a(t(c),o))}for(;++u<f;)n.call(this,l=i[u],u)?c.push([+d.call(this,l,u),+p.call(this,l,u)]):c.length&&(h(),c=[]);return c.length&&h(),s.length?s.join(""):null}return l.x=function(t){return arguments.length?(e=t,l):e},l.y=function(t){return arguments.length?(r=t,l):r},l.defined=function(t){return arguments.length?(n=t,l):n},l.interpolate=function(t){return arguments.length?(i="function"==typeof t?a=t:(a=Ho.get(t)||qo).key,l):i},l.tension=function(t){return arguments.length?(o=t,l):o},l}t.svg.line=function(){return Bo(P)};var Ho=t.map({linear:qo,"linear-closed":Vo,step:function(t){var e=0,r=t.length,n=t[0],a=[n[0],",",n[1]];for(;++e<r;)a.push("H",(n[0]+(n=t[e])[0])/2,"V",n[1]);r>1&&a.push("H",n[0]);return a.join("")},"step-before":Uo,"step-after":Go,basis:Zo,"basis-open":function(t){if(t.length<4)return qo(t);var e,r=[],n=-1,a=t.length,i=[0],o=[0];for(;++n<3;)e=t[n],i.push(e[0]),o.push(e[1]);r.push(Wo($o,i)+","+Wo($o,o)),--n;for(;++n<a;)e=t[n],i.shift(),i.push(e[0]),o.shift(),o.push(e[1]),Ko(r,i,o);return r.join("")},"basis-closed":function(t){var e,r,n=-1,a=t.length,i=a+4,o=[],l=[];for(;++n<4;)r=t[n%a],o.push(r[0]),l.push(r[1]);e=[Wo($o,o),",",Wo($o,l)],--n;for(;++n<i;)r=t[n%a],o.shift(),o.push(r[0]),l.shift(),l.push(r[1]),Ko(e,o,l);return e.join("")},bundle:function(t,e){var r=t.length-1;if(r)for(var n,a,i=t[0][0],o=t[0][1],l=t[r][0]-i,s=t[r][1]-o,c=-1;++c<=r;)n=t[c],a=c/r,n[0]=e*n[0]+(1-e)*(i+a*l),n[1]=e*n[1]+(1-e)*(o+a*s);return Zo(t)},cardinal:function(t,e){return t.length<3?qo(t):t[0]+Yo(t,Xo(t,e))},"cardinal-open":function(t,e){return t.length<4?qo(t):t[1]+Yo(t.slice(1,-1),Xo(t,e))},"cardinal-closed":function(t,e){return t.length<3?Vo(t):t[0]+Yo((t.push(t[0]),t),Xo([t[t.length-2]].concat(t,[t[1]]),e))},monotone:function(t){return t.length<3?qo(t):t[0]+Yo(t,function(t){var e,r,n,a,i=[],o=function(t){var e=0,r=t.length-1,n=[],a=t[0],i=t[1],o=n[0]=tl(a,i);for(;++e<r;)n[e]=(o+(o=tl(a=i,i=t[e+1])))/2;return n[e]=o,n}(t),l=-1,s=t.length-1;for(;++l<s;)e=tl(t[l],t[l+1]),m(e)<kt?o[l]=o[l+1]=0:(r=o[l]/e,n=o[l+1]/e,(a=r*r+n*n)>9&&(a=3*e/Math.sqrt(a),o[l]=a*r,o[l+1]=a*n));l=-1;for(;++l<=s;)a=(t[Math.min(s,l+1)][0]-t[Math.max(0,l-1)][0])/(6*(1+o[l]*o[l])),i.push([a||0,o[l]*a||0]);return i}(t))}});function qo(t){return t.length>1?t.join("L"):t+"Z"}function Vo(t){return t.join("L")+"Z"}function Uo(t){for(var e=0,r=t.length,n=t[0],a=[n[0],",",n[1]];++e<r;)a.push("V",(n=t[e])[1],"H",n[0]);return a.join("")}function Go(t){for(var e=0,r=t.length,n=t[0],a=[n[0],",",n[1]];++e<r;)a.push("H",(n=t[e])[0],"V",n[1]);return a.join("")}function Yo(t,e){if(e.length<1||t.length!=e.length&&t.length!=e.length+2)return qo(t);var r=t.length!=e.length,n="",a=t[0],i=t[1],o=e[0],l=o,s=1;if(r&&(n+="Q"+(i[0]-2*o[0]/3)+","+(i[1]-2*o[1]/3)+","+i[0]+","+i[1],a=t[1],s=2),e.length>1){l=e[1],i=t[s],s++,n+="C"+(a[0]+o[0])+","+(a[1]+o[1])+","+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1];for(var c=2;c<e.length;c++,s++)i=t[s],l=e[c],n+="S"+(i[0]-l[0])+","+(i[1]-l[1])+","+i[0]+","+i[1]}if(r){var u=t[s];n+="Q"+(i[0]+2*l[0]/3)+","+(i[1]+2*l[1]/3)+","+u[0]+","+u[1]}return n}function Xo(t,e){for(var r,n=[],a=(1-e)/2,i=t[0],o=t[1],l=1,s=t.length;++l<s;)r=i,i=o,o=t[l],n.push([a*(o[0]-r[0]),a*(o[1]-r[1])]);return n}function Zo(t){if(t.length<3)return qo(t);var e=1,r=t.length,n=t[0],a=n[0],i=n[1],o=[a,a,a,(n=t[1])[0]],l=[i,i,i,n[1]],s=[a,",",i,"L",Wo($o,o),",",Wo($o,l)];for(t.push(t[r-1]);++e<=r;)n=t[e],o.shift(),o.push(n[0]),l.shift(),l.push(n[1]),Ko(s,o,l);return t.pop(),s.push("L",n),s.join("")}function Wo(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}Ho.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var Qo=[0,2/3,1/3,0],Jo=[0,1/3,2/3,0],$o=[0,1/6,2/3,1/6];function Ko(t,e,r){t.push("C",Wo(Qo,e),",",Wo(Qo,r),",",Wo(Jo,e),",",Wo(Jo,r),",",Wo($o,e),",",Wo($o,r))}function tl(t,e){return(e[1]-t[1])/(e[0]-t[0])}function el(t){for(var e,r,n,a=-1,i=t.length;++a<i;)r=(e=t[a])[0],n=e[1]-Ct,e[0]=r*Math.cos(n),e[1]=r*Math.sin(n);return t}function rl(t){var e=ea,r=ea,n=0,a=ra,i=Yr,o=qo,l=o.key,s=o,c="L",u=.7;function f(l){var f,d,p,h=[],g=[],y=[],v=-1,m=l.length,x=ye(e),b=ye(n),_=e===r?function(){return d}:ye(r),w=n===a?function(){return p}:ye(a);function k(){h.push("M",o(t(y),u),c,s(t(g.reverse()),u),"Z")}for(;++v<m;)i.call(this,f=l[v],v)?(g.push([d=+x.call(this,f,v),p=+b.call(this,f,v)]),y.push([+_.call(this,f,v),+w.call(this,f,v)])):g.length&&(k(),g=[],y=[]);return g.length&&k(),h.length?h.join(""):null}return f.x=function(t){return arguments.length?(e=r=t,f):r},f.x0=function(t){return arguments.length?(e=t,f):e},f.x1=function(t){return arguments.length?(r=t,f):r},f.y=function(t){return arguments.length?(n=a=t,f):a},f.y0=function(t){return arguments.length?(n=t,f):n},f.y1=function(t){return arguments.length?(a=t,f):a},f.defined=function(t){return arguments.length?(i=t,f):i},f.interpolate=function(t){return arguments.length?(l="function"==typeof t?o=t:(o=Ho.get(t)||qo).key,s=o.reverse||o,c=o.closed?"M":"L",f):l},f.tension=function(t){return arguments.length?(u=t,f):u},f}function nl(t){return t.radius}function al(t){return[t.x,t.y]}function il(){return 64}function ol(){return"circle"}function ll(t){var e=Math.sqrt(t/Tt);return"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+-e+"A"+e+","+e+" 0 1,1 0,"+e+"Z"}t.svg.line.radial=function(){var t=Bo(el);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Uo.reverse=Go,Go.reverse=Uo,t.svg.area=function(){return rl(P)},t.svg.area.radial=function(){var t=rl(el);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},t.svg.chord=function(){var t=Hn,e=qn,r=nl,n=Io,a=No;function i(r,n){var a,i,c=o(this,t,r,n),u=o(this,e,r,n);return"M"+c.p0+l(c.r,c.p1,c.a1-c.a0)+(i=u,(a=c).a0==i.a0&&a.a1==i.a1?s(c.r,c.p1,c.r,c.p0):s(c.r,c.p1,u.r,u.p0)+l(u.r,u.p1,u.a1-u.a0)+s(u.r,u.p1,c.r,c.p0))+"Z"}function o(t,e,i,o){var l=e.call(t,i,o),s=r.call(t,l,o),c=n.call(t,l,o)-Ct,u=a.call(t,l,o)-Ct;return{r:s,a0:c,a1:u,p0:[s*Math.cos(c),s*Math.sin(c)],p1:[s*Math.cos(u),s*Math.sin(u)]}}function l(t,e,r){return"A"+t+","+t+" 0 "+ +(r>Tt)+",1 "+e}function s(t,e,r,n){return"Q 0,0 "+n}return i.radius=function(t){return arguments.length?(r=ye(t),i):r},i.source=function(e){return arguments.length?(t=ye(e),i):t},i.target=function(t){return arguments.length?(e=ye(t),i):e},i.startAngle=function(t){return arguments.length?(n=ye(t),i):n},i.endAngle=function(t){return arguments.length?(a=ye(t),i):a},i},t.svg.diagonal=function(){var t=Hn,e=qn,r=al;function n(n,a){var i=t.call(this,n,a),o=e.call(this,n,a),l=(i.y+o.y)/2,s=[i,{x:i.x,y:l},{x:o.x,y:l},o];return"M"+(s=s.map(r))[0]+"C"+s[1]+" "+s[2]+" "+s[3]}return n.source=function(e){return arguments.length?(t=ye(e),n):t},n.target=function(t){return arguments.length?(e=ye(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},t.svg.diagonal.radial=function(){var e=t.svg.diagonal(),r=al,n=e.projection;return e.projection=function(t){return arguments.length?n(function(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-Ct;return[r*Math.cos(n),r*Math.sin(n)]}}(r=t)):r},e},t.svg.symbol=function(){var t=ol,e=il;function r(r,n){return(sl.get(t.call(this,r,n))||ll)(e.call(this,r,n))}return r.type=function(e){return arguments.length?(t=ye(e),r):t},r.size=function(t){return arguments.length?(e=ye(t),r):e},r};var sl=t.map({circle:ll,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*ul)),r=e*ul;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/cl),r=e*cl/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/cl),r=e*cl/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});t.svg.symbolTypes=sl.keys();var cl=Math.sqrt(3),ul=Math.tan(30*St);X.transition=function(t){for(var e,r,n=hl||++vl,a=bl(t),i=[],o=gl||{time:Date.now(),ease:ai,delay:0,duration:250},l=-1,s=this.length;++l<s;){i.push(e=[]);for(var c=this[l],u=-1,f=c.length;++u<f;)(r=c[u])&&_l(r,u,a,n,o),e.push(r)}return pl(i,a,n)},X.interrupt=function(t){return this.each(null==t?fl:dl(bl(t)))};var fl=dl(bl());function dl(t){return function(){var e,r,n;(e=this[t])&&(n=e[r=e.active])&&(n.timer.c=null,n.timer.t=NaN,--e.count?delete e[r]:delete this[t],e.active+=.5,n.event&&n.event.interrupt.call(this,this.__data__,n.index))}}function pl(t,e,r){return q(t,yl),t.namespace=e,t.id=r,t}var hl,gl,yl=[],vl=0;function ml(t,e,r,n){var a=t.id,i=t.namespace;return ut(t,"function"==typeof r?function(t,o,l){t[i][a].tween.set(e,n(r.call(t,t.__data__,o,l)))}:(r=n(r),function(t){t[i][a].tween.set(e,r)}))}function xl(t){return null==t&&(t=""),function(){this.textContent=t}}function bl(t){return null==t?"__transition__":"__transition_"+t+"__"}function _l(t,e,r,n,a){var i,o,l,s,c,u=t[r]||(t[r]={active:0,count:0}),f=u[n];function d(r){var a=u.active,d=u[a];for(var h in d&&(d.timer.c=null,d.timer.t=NaN,--u.count,delete u[a],d.event&&d.event.interrupt.call(t,t.__data__,d.index)),u)if(+h<n){var g=u[h];g.timer.c=null,g.timer.t=NaN,--u.count,delete u[h]}o.c=p,Me(function(){return o.c&&p(r||1)&&(o.c=null,o.t=NaN),1},0,i),u.active=n,f.event&&f.event.start.call(t,t.__data__,e),c=[],f.tween.forEach(function(r,n){(n=n.call(t,t.__data__,e))&&c.push(n)}),s=f.ease,l=f.duration}function p(a){for(var i=a/l,o=s(i),d=c.length;d>0;)c[--d].call(t,o);if(i>=1)return f.event&&f.event.end.call(t,t.__data__,e),--u.count?delete u[n]:delete t[r],1}f||(i=a.time,o=Me(function(t){var e=f.delay;if(o.t=e+i,e<=t)return d(t-e);o.c=d},0,i),f=u[n]={tween:new b,time:i,timer:o,delay:a.delay,duration:a.duration,ease:a.ease,index:e},a=null,++u.count)}yl.call=X.call,yl.empty=X.empty,yl.node=X.node,yl.size=X.size,t.transition=function(e,r){return e&&e.transition?hl?e.transition(r):e:t.selection().transition(e)},t.transition.prototype=yl,yl.select=function(t){var e,r,n,a=this.id,i=this.namespace,o=[];t=Z(t);for(var l=-1,s=this.length;++l<s;){o.push(e=[]);for(var c=this[l],u=-1,f=c.length;++u<f;)(n=c[u])&&(r=t.call(n,n.__data__,u,l))?("__data__"in n&&(r.__data__=n.__data__),_l(r,u,i,a,n[i][a]),e.push(r)):e.push(null)}return pl(o,i,a)},yl.selectAll=function(t){var e,r,n,a,i,o=this.id,l=this.namespace,s=[];t=W(t);for(var c=-1,u=this.length;++c<u;)for(var f=this[c],d=-1,p=f.length;++d<p;)if(n=f[d]){i=n[l][o],r=t.call(n,n.__data__,d,c),s.push(e=[]);for(var h=-1,g=r.length;++h<g;)(a=r[h])&&_l(a,h,l,o,i),e.push(a)}return pl(s,l,o)},yl.filter=function(t){var e,r,n=[];"function"!=typeof t&&(t=ct(t));for(var a=0,i=this.length;a<i;a++){n.push(e=[]);for(var o,l=0,s=(o=this[a]).length;l<s;l++)(r=o[l])&&t.call(r,r.__data__,l,a)&&e.push(r)}return pl(n,this.namespace,this.id)},yl.tween=function(t,e){var r=this.id,n=this.namespace;return arguments.length<2?this.node()[n][r].tween.get(t):ut(this,null==e?function(e){e[n][r].tween.remove(t)}:function(a){a[n][r].tween.set(t,e)})},yl.attr=function(e,r){if(arguments.length<2){for(r in e)this.attr(r,e[r]);return this}var n="transform"==e?gi:Wa,a=t.ns.qualify(e);function i(){this.removeAttribute(a)}function o(){this.removeAttributeNS(a.space,a.local)}return ml(this,"attr."+e,r,a.local?function(t){return null==t?o:(t+="",function(){var e,r=this.getAttributeNS(a.space,a.local);return r!==t&&(e=n(r,t),function(t){this.setAttributeNS(a.space,a.local,e(t))})})}:function(t){return null==t?i:(t+="",function(){var e,r=this.getAttribute(a);return r!==t&&(e=n(r,t),function(t){this.setAttribute(a,e(t))})})})},yl.attrTween=function(e,r){var n=t.ns.qualify(e);return this.tween("attr."+e,n.local?function(t,e){var a=r.call(this,t,e,this.getAttributeNS(n.space,n.local));return a&&function(t){this.setAttributeNS(n.space,n.local,a(t))}}:function(t,e){var a=r.call(this,t,e,this.getAttribute(n));return a&&function(t){this.setAttribute(n,a(t))}})},yl.style=function(t,e,r){var n=arguments.length;if(n<3){if("string"!=typeof t){for(r in n<2&&(e=""),t)this.style(r,t[r],e);return this}r=""}function a(){this.style.removeProperty(t)}return ml(this,"style."+t,e,function(e){return null==e?a:(e+="",function(){var n,a=o(this).getComputedStyle(this,null).getPropertyValue(t);return a!==e&&(n=Wa(a,e),function(e){this.style.setProperty(t,n(e),r)})})})},yl.styleTween=function(t,e,r){return arguments.length<3&&(r=""),this.tween("style."+t,function(n,a){var i=e.call(this,n,a,o(this).getComputedStyle(this,null).getPropertyValue(t));return i&&function(e){this.style.setProperty(t,i(e),r)}})},yl.text=function(t){return ml(this,"text",t,xl)},yl.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})},yl.ease=function(e){var r=this.id,n=this.namespace;return arguments.length<1?this.node()[n][r].ease:("function"!=typeof e&&(e=t.ease.apply(t,arguments)),ut(this,function(t){t[n][r].ease=e}))},yl.delay=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].delay:ut(this,"function"==typeof t?function(n,a,i){n[r][e].delay=+t.call(n,n.__data__,a,i)}:(t=+t,function(n){n[r][e].delay=t}))},yl.duration=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].duration:ut(this,"function"==typeof t?function(n,a,i){n[r][e].duration=Math.max(1,t.call(n,n.__data__,a,i))}:(t=Math.max(1,t),function(n){n[r][e].duration=t}))},yl.each=function(e,r){var n=this.id,a=this.namespace;if(arguments.length<2){var i=gl,o=hl;try{hl=n,ut(this,function(t,r,i){gl=t[a][n],e.call(t,t.__data__,r,i)})}finally{gl=i,hl=o}}else ut(this,function(i){var o=i[a][n];(o.event||(o.event=t.dispatch("start","end","interrupt"))).on(e,r)});return this},yl.transition=function(){for(var t,e,r,n=this.id,a=++vl,i=this.namespace,o=[],l=0,s=this.length;l<s;l++){o.push(t=[]);for(var c,u=0,f=(c=this[l]).length;u<f;u++)(e=c[u])&&_l(e,u,i,a,{time:(r=e[i][n]).time,ease:r.ease,delay:r.delay+r.duration,duration:r.duration}),t.push(e)}return pl(o,i,a)},t.svg.axis=function(){var e,r=t.scale.linear(),a=wl,i=6,o=6,l=3,s=[10],c=null;function u(n){n.each(function(){var n,u=t.select(this),f=this.__chart__||r,d=this.__chart__=r.copy(),p=null==c?d.ticks?d.ticks.apply(d,s):d.domain():c,h=null==e?d.tickFormat?d.tickFormat.apply(d,s):P:e,g=u.selectAll(".tick").data(p,d),y=g.enter().insert("g",".domain").attr("class","tick").style("opacity",kt),v=t.transition(g.exit()).style("opacity",kt).remove(),m=t.transition(g.order()).style("opacity",1),x=Math.max(i,0)+l,b=uo(d),_=u.selectAll(".domain").data([0]),w=(_.enter().append("path").attr("class","domain"),t.transition(_));y.append("line"),y.append("text");var k,M,T,A,L=y.select("line"),C=m.select("line"),S=g.select("text").text(h),O=y.select("text"),D=m.select("text"),z="top"===a||"left"===a?-1:1;if("bottom"===a||"top"===a?(n=Ml,k="x",T="y",M="x2",A="y2",S.attr("dy",z<0?"0em":".71em").style("text-anchor","middle"),w.attr("d","M"+b[0]+","+z*o+"V0H"+b[1]+"V"+z*o)):(n=Tl,k="y",T="x",M="y2",A="x2",S.attr("dy",".32em").style("text-anchor",z<0?"end":"start"),w.attr("d","M"+z*o+","+b[0]+"H0V"+b[1]+"H"+z*o)),L.attr(A,z*i),O.attr(T,z*x),C.attr(M,0).attr(A,z*i),D.attr(k,0).attr(T,z*x),d.rangeBand){var E=d,I=E.rangeBand()/2;f=d=function(t){return E(t)+I}}else f.rangeBand?f=d:v.call(n,d,f);y.call(n,f,d),m.call(n,d,d)})}return u.scale=function(t){return arguments.length?(r=t,u):r},u.orient=function(t){return arguments.length?(a=t in kl?t+"":wl,u):a},u.ticks=function(){return arguments.length?(s=n(arguments),u):s},u.tickValues=function(t){return arguments.length?(c=t,u):c},u.tickFormat=function(t){return arguments.length?(e=t,u):e},u.tickSize=function(t){var e=arguments.length;return e?(i=+t,o=+arguments[e-1],u):i},u.innerTickSize=function(t){return arguments.length?(i=+t,u):i},u.outerTickSize=function(t){return arguments.length?(o=+t,u):o},u.tickPadding=function(t){return arguments.length?(l=+t,u):l},u.tickSubdivide=function(){return arguments.length&&u},u};var wl="bottom",kl={top:1,right:1,bottom:1,left:1};function Ml(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate("+(isFinite(n)?n:r(t))+",0)"})}function Tl(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate(0,"+(isFinite(n)?n:r(t))+")"})}t.svg.brush=function(){var e,r,n=B(d,"brushstart","brush","brushend"),a=null,i=null,l=[0,0],s=[0,0],c=!0,u=!0,f=Ll[0];function d(e){e.each(function(){var e=t.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",y).on("touchstart.brush",y),r=e.selectAll(".background").data([0]);r.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),e.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var n=e.selectAll(".resize").data(f,P);n.exit().remove(),n.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Al[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),n.style("display",d.empty()?"none":null);var o,l=t.transition(e),s=t.transition(r);a&&(o=uo(a),s.attr("x",o[0]).attr("width",o[1]-o[0]),h(l)),i&&(o=uo(i),s.attr("y",o[0]).attr("height",o[1]-o[0]),g(l)),p(l)})}function p(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+l[+/e$/.test(t)]+","+s[+/^s/.test(t)]+")"})}function h(t){t.select(".extent").attr("x",l[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",l[1]-l[0])}function g(t){t.select(".extent").attr("y",s[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",s[1]-s[0])}function y(){var f,y,v=this,m=t.select(t.event.target),x=n.of(v,arguments),b=t.select(v),_=m.datum(),w=!/^(n|s)$/.test(_)&&a,k=!/^(e|w)$/.test(_)&&i,M=m.classed("extent"),T=xt(v),A=t.mouse(v),L=t.select(o(v)).on("keydown.brush",function(){32==t.event.keyCode&&(M||(f=null,A[0]-=l[1],A[1]-=s[1],M=2),F())}).on("keyup.brush",function(){32==t.event.keyCode&&2==M&&(A[0]+=l[1],A[1]+=s[1],M=0,F())});if(t.event.changedTouches?L.on("touchmove.brush",O).on("touchend.brush",D):L.on("mousemove.brush",O).on("mouseup.brush",D),b.interrupt().selectAll("*").interrupt(),M)A[0]=l[0]-A[0],A[1]=s[0]-A[1];else if(_){var C=+/w$/.test(_),S=+/^n/.test(_);y=[l[1-C]-A[0],s[1-S]-A[1]],A[0]=l[C],A[1]=s[S]}else t.event.altKey&&(f=A.slice());function O(){var e=t.mouse(v),r=!1;y&&(e[0]+=y[0],e[1]+=y[1]),M||(t.event.altKey?(f||(f=[(l[0]+l[1])/2,(s[0]+s[1])/2]),A[0]=l[+(e[0]<f[0])],A[1]=s[+(e[1]<f[1])]):f=null),w&&P(e,a,0)&&(h(b),r=!0),k&&P(e,i,1)&&(g(b),r=!0),r&&(p(b),x({type:"brush",mode:M?"move":"resize"}))}function P(t,n,a){var i,o,d=uo(n),p=d[0],h=d[1],g=A[a],y=a?s:l,v=y[1]-y[0];if(M&&(p-=g,h-=v+g),i=(a?u:c)?Math.max(p,Math.min(h,t[a])):t[a],M?o=(i+=g)+v:(f&&(g=Math.max(p,Math.min(h,2*f[a]-i))),g<i?(o=i,i=g):o=g),y[0]!=i||y[1]!=o)return a?r=null:e=null,y[0]=i,y[1]=o,!0}function D(){O(),b.style("pointer-events","all").selectAll(".resize").style("display",d.empty()?"none":null),t.select("body").style("cursor",null),L.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),T(),x({type:"brushend"})}b.style("pointer-events","none").selectAll(".resize").style("display",null),t.select("body").style("cursor",m.style("cursor")),x({type:"brushstart"}),O()}return d.event=function(a){a.each(function(){var a=n.of(this,arguments),i={x:l,y:s,i:e,j:r},o=this.__chart__||i;this.__chart__=i,hl?t.select(this).transition().each("start.brush",function(){e=o.i,r=o.j,l=o.x,s=o.y,a({type:"brushstart"})}).tween("brush:brush",function(){var t=Qa(l,i.x),n=Qa(s,i.y);return e=r=null,function(e){l=i.x=t(e),s=i.y=n(e),a({type:"brush",mode:"resize"})}}).each("end.brush",function(){e=i.i,r=i.j,a({type:"brush",mode:"resize"}),a({type:"brushend"})}):(a({type:"brushstart"}),a({type:"brush",mode:"resize"}),a({type:"brushend"}))})},d.x=function(t){return arguments.length?(f=Ll[!(a=t)<<1|!i],d):a},d.y=function(t){return arguments.length?(f=Ll[!a<<1|!(i=t)],d):i},d.clamp=function(t){return arguments.length?(a&&i?(c=!!t[0],u=!!t[1]):a?c=!!t:i&&(u=!!t),d):a&&i?[c,u]:a?c:i?u:null},d.extent=function(t){var n,o,c,u,f;return arguments.length?(a&&(n=t[0],o=t[1],i&&(n=n[0],o=o[0]),e=[n,o],a.invert&&(n=a(n),o=a(o)),o<n&&(f=n,n=o,o=f),n==l[0]&&o==l[1]||(l=[n,o])),i&&(c=t[0],u=t[1],a&&(c=c[1],u=u[1]),r=[c,u],i.invert&&(c=i(c),u=i(u)),u<c&&(f=c,c=u,u=f),c==s[0]&&u==s[1]||(s=[c,u])),d):(a&&(e?(n=e[0],o=e[1]):(n=l[0],o=l[1],a.invert&&(n=a.invert(n),o=a.invert(o)),o<n&&(f=n,n=o,o=f))),i&&(r?(c=r[0],u=r[1]):(c=s[0],u=s[1],i.invert&&(c=i.invert(c),u=i.invert(u)),u<c&&(f=c,c=u,u=f))),a&&i?[[n,c],[o,u]]:a?[n,o]:i&&[c,u])},d.clear=function(){return d.empty()||(l=[0,0],s=[0,0],e=r=null),d},d.empty=function(){return!!a&&l[0]==l[1]||!!i&&s[0]==s[1]},t.rebind(d,n,"on")};var Al={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Ll=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Cl=ze.format=lr.timeFormat,Sl=Cl.utc,Ol=Sl("%Y-%m-%dT%H:%M:%S.%LZ");function Pl(t){return t.toISOString()}function Dl(e,r,n){function a(t){return e(t)}function i(e,n){var a=(e[1]-e[0])/n,i=t.bisect(El,a);return i==El.length?[r.year,xo(e.map(function(t){return t/31536e6}),n)[2]]:i?r[a/El[i-1]<El[i]/a?i-1:i]:[Rl,xo(e,n)[2]]}return a.invert=function(t){return zl(e.invert(t))},a.domain=function(t){return arguments.length?(e.domain(t),a):e.domain().map(zl)},a.nice=function(t,e){var r=a.domain(),n=co(r),o=null==t?i(n,10):"number"==typeof t&&i(n,t);function l(r){return!isNaN(r)&&!t.range(r,zl(+r+1),e).length}return o&&(t=o[0],e=o[1]),a.domain(po(r,e>1?{floor:function(e){for(;l(e=t.floor(e));)e=zl(e-1);return e},ceil:function(e){for(;l(e=t.ceil(e));)e=zl(+e+1);return e}}:t))},a.ticks=function(t,e){var r=co(a.domain()),n=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return n&&(t=n[0],e=n[1]),t.range(r[0],zl(+r[1]+1),e<1?1:e)},a.tickFormat=function(){return n},a.copy=function(){return Dl(e.copy(),r,n)},vo(a,e)}function zl(t){return new Date(t)}Cl.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Pl:Ol,Pl.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},Pl.toString=Ol.toString,ze.second=Re(function(t){return new Ee(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),ze.seconds=ze.second.range,ze.seconds.utc=ze.second.utc.range,ze.minute=Re(function(t){return new Ee(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),ze.minutes=ze.minute.range,ze.minutes.utc=ze.minute.utc.range,ze.hour=Re(function(t){var e=t.getTimezoneOffset()/60;return new Ee(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),ze.hours=ze.hour.range,ze.hours.utc=ze.hour.utc.range,ze.month=Re(function(t){return(t=ze.day(t)).setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),ze.months=ze.month.range,ze.months.utc=ze.month.utc.range;var El=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Il=[[ze.second,1],[ze.second,5],[ze.second,15],[ze.second,30],[ze.minute,1],[ze.minute,5],[ze.minute,15],[ze.minute,30],[ze.hour,1],[ze.hour,3],[ze.hour,6],[ze.hour,12],[ze.day,1],[ze.day,2],[ze.week,1],[ze.month,1],[ze.month,3],[ze.year,1]],Nl=Cl.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Yr]]),Rl={range:function(e,r,n){return t.range(Math.ceil(e/n)*n,+r,n).map(zl)},floor:P,ceil:P};Il.year=ze.year,ze.scale=function(){return Dl(t.scale.linear(),Il,Nl)};var Fl=Il.map(function(t){return[t[0].utc,t[1]]}),jl=Sl.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Yr]]);function Bl(t){return JSON.parse(t.responseText)}function Hl(t){var e=a.createRange();return e.selectNode(a.body),e.createContextualFragment(t.responseText)}Fl.year=ze.year.utc,ze.scale.utc=function(){return Dl(t.scale.linear(),Fl,jl)},t.text=ve(function(t){return t.responseText}),t.json=function(t,e){return me(t,"application/json",Bl,e)},t.html=function(t,e){return me(t,"text/html",Hl,e)},t.xml=ve(function(t){return t.responseXML}),"object"==typeof e&&e.exports?e.exports=t:this.d3=t}()},{}],11:[function(t,e,r){(function(n,a){!function(t,n){"object"==typeof r&&"undefined"!=typeof e?e.exports=n():t.ES6Promise=n()}(this,function(){"use strict";function e(t){return"function"==typeof t}var r=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},i=0,o=void 0,l=void 0,s=function(t,e){g[i]=t,g[i+1]=e,2===(i+=2)&&(l?l(y):_())};var c="undefined"!=typeof window?window:void 0,u=c||{},f=u.MutationObserver||u.WebKitMutationObserver,d="undefined"==typeof self&&"undefined"!=typeof n&&"[object process]"==={}.toString.call(n),p="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function h(){var t=setTimeout;return function(){return t(y,1)}}var g=new Array(1e3);function y(){for(var t=0;t<i;t+=2){(0,g[t])(g[t+1]),g[t]=void 0,g[t+1]=void 0}i=0}var v,m,x,b,_=void 0;function w(t,e){var r=arguments,n=this,a=new this.constructor(T);void 0===a[M]&&q(a);var i,o=n._state;return o?(i=r[o-1],s(function(){return B(o,a,i,n._result)})):N(n,a,t,e),a}function k(t){if(t&&"object"==typeof t&&t.constructor===this)return t;var e=new this(T);return D(e,t),e}d?_=function(){return n.nextTick(y)}:f?(m=0,x=new f(y),b=document.createTextNode(""),x.observe(b,{characterData:!0}),_=function(){b.data=m=++m%2}):p?((v=new MessageChannel).port1.onmessage=y,_=function(){return v.port2.postMessage(0)}):_=void 0===c&&"function"==typeof t?function(){try{var e=t("vertx");return o=e.runOnLoop||e.runOnContext,function(){o(y)}}catch(t){return h()}}():h();var M=Math.random().toString(36).substring(16);function T(){}var A=void 0,L=1,C=2,S=new F;function O(t){try{return t.then}catch(t){return S.error=t,S}}function P(t,r,n){r.constructor===t.constructor&&n===w&&r.constructor.resolve===k?function(t,e){e._state===L?E(t,e._result):e._state===C?I(t,e._result):N(e,void 0,function(e){return D(t,e)},function(e){return I(t,e)})}(t,r):n===S?I(t,S.error):void 0===n?E(t,r):e(n)?function(t,e,r){s(function(t){var n=!1,a=function(t,e,r,n){try{t.call(e,r,n)}catch(t){return t}}(r,e,function(r){n||(n=!0,e!==r?D(t,r):E(t,r))},function(e){n||(n=!0,I(t,e))},t._label);!n&&a&&(n=!0,I(t,a))},t)}(t,r,n):E(t,r)}function D(t,e){var r;t===e?I(t,new TypeError("You cannot resolve a promise with itself")):"function"==typeof(r=e)||"object"==typeof r&&null!==r?P(t,e,O(e)):E(t,e)}function z(t){t._onerror&&t._onerror(t._result),R(t)}function E(t,e){t._state===A&&(t._result=e,t._state=L,0!==t._subscribers.length&&s(R,t))}function I(t,e){t._state===A&&(t._state=C,t._result=e,s(z,t))}function N(t,e,r,n){var a=t._subscribers,i=a.length;t._onerror=null,a[i]=e,a[i+L]=r,a[i+C]=n,0===i&&t._state&&s(R,t)}function R(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var n=void 0,a=void 0,i=t._result,o=0;o<e.length;o+=3)n=e[o],a=e[o+r],n?B(r,n,a,i):a(i);t._subscribers.length=0}}function F(){this.error=null}var j=new F;function B(t,r,n,a){var i=e(n),o=void 0,l=void 0,s=void 0,c=void 0;if(i){if((o=function(t,e){try{return t(e)}catch(t){return j.error=t,j}}(n,a))===j?(c=!0,l=o.error,o=null):s=!0,r===o)return void I(r,new TypeError("A promises callback cannot return that same promise."))}else o=a,s=!0;r._state!==A||(i&&s?D(r,o):c?I(r,l):t===L?E(r,o):t===C&&I(r,o))}var H=0;function q(t){t[M]=H++,t._state=void 0,t._result=void 0,t._subscribers=[]}function V(t,e){this._instanceConstructor=t,this.promise=new t(T),this.promise[M]||q(this.promise),r(e)?(this._input=e,this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?E(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&E(this.promise,this._result))):I(this.promise,new Error("Array Methods must be provided an Array"))}function U(t){this[M]=H++,this._result=this._state=void 0,this._subscribers=[],T!==t&&("function"!=typeof t&&function(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}(),this instanceof U?function(t,e){try{e(function(e){D(t,e)},function(e){I(t,e)})}catch(e){I(t,e)}}(this,t):function(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}())}function G(){var t=void 0;if("undefined"!=typeof a)t=a;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(t){throw new Error("polyfill failed because global object is unavailable in this environment")}var e=t.Promise;if(e){var r=null;try{r=Object.prototype.toString.call(e.resolve())}catch(t){}if("[object Promise]"===r&&!e.cast)return}t.Promise=U}return V.prototype._enumerate=function(){for(var t=this.length,e=this._input,r=0;this._state===A&&r<t;r++)this._eachEntry(e[r],r)},V.prototype._eachEntry=function(t,e){var r=this._instanceConstructor,n=r.resolve;if(n===k){var a=O(t);if(a===w&&t._state!==A)this._settledAt(t._state,e,t._result);else if("function"!=typeof a)this._remaining--,this._result[e]=t;else if(r===U){var i=new r(T);P(i,t,a),this._willSettleAt(i,e)}else this._willSettleAt(new r(function(e){return e(t)}),e)}else this._willSettleAt(n(t),e)},V.prototype._settledAt=function(t,e,r){var n=this.promise;n._state===A&&(this._remaining--,t===C?I(n,r):this._result[e]=r),0===this._remaining&&E(n,this._result)},V.prototype._willSettleAt=function(t,e){var r=this;N(t,void 0,function(t){return r._settledAt(L,e,t)},function(t){return r._settledAt(C,e,t)})},U.all=function(t){return new V(this,t).promise},U.race=function(t){var e=this;return r(t)?new e(function(r,n){for(var a=t.length,i=0;i<a;i++)e.resolve(t[i]).then(r,n)}):new e(function(t,e){return e(new TypeError("You must pass an array to race."))})},U.resolve=k,U.reject=function(t){var e=new this(T);return I(e,t),e},U._setScheduler=function(t){l=t},U._setAsap=function(t){s=t},U._asap=s,U.prototype={constructor:U,then:w,catch:function(t){return this.then(null,t)}},G(),U.polyfill=G,U.Promise=U,U})}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:27}],12:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function a(t){return"function"==typeof t}function i(t){return"object"==typeof t&&null!==t}function o(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,l,s,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||i(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var u=new Error('Uncaught, unspecified "error" event. ('+e+")");throw u.context=e,u}if(o(r=this._events[t]))return!1;if(a(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:l=Array.prototype.slice.call(arguments,1),r.apply(this,l)}else if(i(r))for(l=Array.prototype.slice.call(arguments,1),n=(c=r.slice()).length,s=0;s<n;s++)c[s].apply(this,l);return!0},n.prototype.addListener=function(t,e){var r;if(!a(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,a(e.listener)?e.listener:e),this._events[t]?i(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,i(this._events[t])&&!this._events[t].warned&&(r=o(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){if(!a(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var r,n,o,l;if(!a(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(o=(r=this._events[t]).length,n=-1,r===e||a(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(i(r)){for(l=o;l-- >0;)if(r[l]===e||r[l].listener&&r[l].listener===e){n=l;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(a(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){return this._events&&this._events[t]?a(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(a(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],13:[function(t,e,r){"use strict";e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(0===(t=+t)&&function(t){for(var e,r=t.length,n=0;n<r;n++)if(((e=t.charCodeAt(n))<9||e>13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(e<8192||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}(r))return!1}else if("number"!==e)return!1;return t-t<1}},{}],14:[function(t,e,r){e.exports=function(t,e){var r=e[0],n=e[1],a=e[2],i=e[3],o=r+r,l=n+n,s=a+a,c=r*o,u=n*o,f=n*l,d=a*o,p=a*l,h=a*s,g=i*o,y=i*l,v=i*s;return t[0]=1-f-h,t[1]=u+v,t[2]=d-y,t[3]=0,t[4]=u-v,t[5]=1-c-h,t[6]=p+g,t[7]=0,t[8]=d+y,t[9]=p-g,t[10]=1-c-f,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}},{}],15:[function(t,e,r){(function(r){"use strict";var n,a=t("is-browser");n="function"==typeof r.matchMedia?!r.matchMedia("(hover: none)").matches:a,e.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"is-browser":17}],16:[function(t,e,r){"use strict";var n=t("is-browser");e.exports=n&&function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(e){t=!1}return t}()},{"is-browser":17}],17:[function(t,e,r){e.exports=!0},{}],18:[function(t,e,r){var n={left:0,top:0};e.exports=function(t,e,r){e=e||t.currentTarget||t.srcElement,Array.isArray(r)||(r=[0,0]);var a=t.clientX||0,i=t.clientY||0,o=(l=e,l===window||l===document||l===document.body?n:l.getBoundingClientRect());var l;return r[0]=a-o.left,r[1]=i-o.top,r}},{}],19:[function(t,e,r){var n,a=t("./lib/build-log"),i=t("./lib/epsilon"),o=t("./lib/intersecter"),l=t("./lib/segment-chainer"),s=t("./lib/segment-selector"),c=t("./lib/geojson"),u=!1,f=i();function d(t,e,r){var a=n.segments(t),i=n.segments(e),o=r(n.combine(a,i));return n.polygon(o)}n={buildLog:function(t){return!0===t?u=a():!1===t&&(u=!1),!1!==u&&u.list},epsilon:function(t){return f.epsilon(t)},segments:function(t){var e=o(!0,f,u);return t.regions.forEach(e.addRegion),{segments:e.calculate(t.inverted),inverted:t.inverted}},combine:function(t,e){return{combined:o(!1,f,u).calculate(t.segments,t.inverted,e.segments,e.inverted),inverted1:t.inverted,inverted2:e.inverted}},selectUnion:function(t){return{segments:s.union(t.combined,u),inverted:t.inverted1||t.inverted2}},selectIntersect:function(t){return{segments:s.intersect(t.combined,u),inverted:t.inverted1&&t.inverted2}},selectDifference:function(t){return{segments:s.difference(t.combined,u),inverted:t.inverted1&&!t.inverted2}},selectDifferenceRev:function(t){return{segments:s.differenceRev(t.combined,u),inverted:!t.inverted1&&t.inverted2}},selectXor:function(t){return{segments:s.xor(t.combined,u),inverted:t.inverted1!==t.inverted2}},polygon:function(t){return{regions:l(t.segments,f,u),inverted:t.inverted}},polygonFromGeoJSON:function(t){return c.toPolygon(n,t)},polygonToGeoJSON:function(t){return c.fromPolygon(n,f,t)},union:function(t,e){return d(t,e,n.selectUnion)},intersect:function(t,e){return d(t,e,n.selectIntersect)},difference:function(t,e){return d(t,e,n.selectDifference)},differenceRev:function(t,e){return d(t,e,n.selectDifferenceRev)},xor:function(t,e){return d(t,e,n.selectXor)}},"object"==typeof window&&(window.PolyBool=n),e.exports=n},{"./lib/build-log":20,"./lib/epsilon":21,"./lib/geojson":22,"./lib/intersecter":23,"./lib/segment-chainer":25,"./lib/segment-selector":26}],20:[function(t,e,r){e.exports=function(){var t,e=0,r=!1;function n(e,r){return t.list.push({type:e,data:r?JSON.parse(JSON.stringify(r)):void 0}),t}return t={list:[],segmentId:function(){return e++},checkIntersection:function(t,e){return n("check",{seg1:t,seg2:e})},segmentChop:function(t,e){return n("div_seg",{seg:t,pt:e}),n("chop",{seg:t,pt:e})},statusRemove:function(t){return n("pop_seg",{seg:t})},segmentUpdate:function(t){return n("seg_update",{seg:t})},segmentNew:function(t,e){return n("new_seg",{seg:t,primary:e})},segmentRemove:function(t){return n("rem_seg",{seg:t})},tempStatus:function(t,e,r){return n("temp_status",{seg:t,above:e,below:r})},rewind:function(t){return n("rewind",{seg:t})},status:function(t,e,r){return n("status",{seg:t,above:e,below:r})},vert:function(e){return e===r?t:(r=e,n("vert",{x:e}))},log:function(t){return"string"!=typeof t&&(t=JSON.stringify(t,!1," ")),n("log",{txt:t})},reset:function(){return n("reset")},selected:function(t){return n("selected",{segs:t})},chainStart:function(t){return n("chain_start",{seg:t})},chainRemoveHead:function(t,e){return n("chain_rem_head",{index:t,pt:e})},chainRemoveTail:function(t,e){return n("chain_rem_tail",{index:t,pt:e})},chainNew:function(t,e){return n("chain_new",{pt1:t,pt2:e})},chainMatch:function(t){return n("chain_match",{index:t})},chainClose:function(t){return n("chain_close",{index:t})},chainAddHead:function(t,e){return n("chain_add_head",{index:t,pt:e})},chainAddTail:function(t,e){return n("chain_add_tail",{index:t,pt:e})},chainConnect:function(t,e){return n("chain_con",{index1:t,index2:e})},chainReverse:function(t){return n("chain_rev",{index:t})},chainJoin:function(t,e){return n("chain_join",{index1:t,index2:e})},done:function(){return n("done")}}}},{}],21:[function(t,e,r){e.exports=function(t){"number"!=typeof t&&(t=1e-10);var e={epsilon:function(e){return"number"==typeof e&&(t=e),t},pointAboveOrOnLine:function(e,r,n){var a=r[0],i=r[1],o=n[0],l=n[1],s=e[0];return(o-a)*(e[1]-i)-(l-i)*(s-a)>=-t},pointBetween:function(e,r,n){var a=e[1]-r[1],i=n[0]-r[0],o=e[0]-r[0],l=n[1]-r[1],s=o*i+a*l;return!(s<t||s-(i*i+l*l)>-t)},pointsSameX:function(e,r){return Math.abs(e[0]-r[0])<t},pointsSameY:function(e,r){return Math.abs(e[1]-r[1])<t},pointsSame:function(t,r){return e.pointsSameX(t,r)&&e.pointsSameY(t,r)},pointsCompare:function(t,r){return e.pointsSameX(t,r)?e.pointsSameY(t,r)?0:t[1]<r[1]?-1:1:t[0]<r[0]?-1:1},pointsCollinear:function(e,r,n){var a=e[0]-r[0],i=e[1]-r[1],o=r[0]-n[0],l=r[1]-n[1];return Math.abs(a*l-o*i)<t},linesIntersect:function(e,r,n,a){var i=r[0]-e[0],o=r[1]-e[1],l=a[0]-n[0],s=a[1]-n[1],c=i*s-o*l;if(Math.abs(c)<t)return!1;var u=e[0]-n[0],f=e[1]-n[1],d=(l*f-s*u)/c,p=(i*f-o*u)/c,h={alongA:0,alongB:0,pt:[e[0]+d*i,e[1]+d*o]};return h.alongA=d<=-t?-2:d<t?-1:d-1<=-t?0:d-1<t?1:2,h.alongB=p<=-t?-2:p<t?-1:p-1<=-t?0:p-1<t?1:2,h},pointInsideRegion:function(e,r){for(var n=e[0],a=e[1],i=r[r.length-1][0],o=r[r.length-1][1],l=!1,s=0;s<r.length;s++){var c=r[s][0],u=r[s][1];u-a>t!=o-a>t&&(i-c)*(a-u)/(o-u)+c-n>t&&(l=!l),i=c,o=u}return l}};return e}},{}],22:[function(t,e,r){var n={toPolygon:function(t,e){function r(e){if(e.length<=0)return t.segments({inverted:!1,regions:[]});function r(e){var r=e.slice(0,e.length-1);return t.segments({inverted:!1,regions:[r]})}for(var n=r(e[0]),a=1;a<e.length;a++)n=t.selectDifference(t.combine(n,r(e[a])));return n}if("Polygon"===e.type)return t.polygon(r(e.coordinates));if("MultiPolygon"===e.type){for(var n=t.segments({inverted:!1,regions:[]}),a=0;a<e.coordinates.length;a++)n=t.selectUnion(t.combine(n,r(e.coordinates[a])));return t.polygon(n)}throw new Error("PolyBool: Cannot convert GeoJSON object to PolyBool polygon")},fromPolygon:function(t,e,r){function n(t,r){return e.pointInsideRegion([.5*(t[0][0]+t[1][0]),.5*(t[0][1]+t[1][1])],r)}function a(t){return{region:t,children:[]}}r=t.polygon(t.segments(r));var i=a(null);function o(t,e){for(var r=0;r<t.children.length;r++){if(n(e,(l=t.children[r]).region))return void o(l,e)}var i=a(e);for(r=0;r<t.children.length;r++){var l;n((l=t.children[r]).region,e)&&(i.children.push(l),t.children.splice(r,1),r--)}t.children.push(i)}for(var l=0;l<r.regions.length;l++){var s=r.regions[l];s.length<3||o(i,s)}function c(t,e){for(var r=0,n=t[t.length-1][0],a=t[t.length-1][1],i=[],o=0;o<t.length;o++){var l=t[o][0],s=t[o][1];i.push([l,s]),r+=s*n-l*a,n=l,a=s}return r<0!==e&&i.reverse(),i.push([i[0][0],i[0][1]]),i}var u=[];function f(t){var e=[c(t.region,!1)];u.push(e);for(var r=0;r<t.children.length;r++)e.push(d(t.children[r]))}function d(t){for(var e=0;e<t.children.length;e++)f(t.children[e]);return c(t.region,!0)}for(l=0;l<i.children.length;l++)f(i.children[l]);return u.length<=0?{type:"Polygon",coordinates:[]}:1==u.length?{type:"Polygon",coordinates:u[0]}:{type:"MultiPolygon",coordinates:u}}};e.exports=n},{}],23:[function(t,e,r){var n=t("./linked-list");e.exports=function(t,e,r){function a(t,e,n){return{id:r?r.segmentId():-1,start:t,end:e,myFill:{above:n.myFill.above,below:n.myFill.below},otherFill:null}}var i=n.create();function o(t,r){i.insertBefore(t,function(n){return function(t,r,n,a,i,o){var l=e.pointsCompare(r,i);return 0!==l?l:e.pointsSame(n,o)?0:t!==a?t?1:-1:e.pointAboveOrOnLine(n,a?i:o,a?o:i)?1:-1}(t.isStart,t.pt,r,n.isStart,n.pt,n.other.pt)<0})}function l(t,e){var r=function(t,e){var r=n.node({isStart:!0,pt:t.start,seg:t,primary:e,other:null,status:null});return o(r,t.end),r}(t,e);return function(t,e,r){var a=n.node({isStart:!1,pt:e.end,seg:e,primary:r,other:t,status:null});t.other=a,o(a,t.pt)}(r,t,e),r}function s(t,e){var n=a(e,t.seg.end,t.seg);return function(t,e){r&&r.segmentChop(t.seg,e),t.other.remove(),t.seg.end=e,t.other.pt=e,o(t.other,t.pt)}(t,e),l(n,t.primary)}function c(a,o){var l=n.create();function c(t){return l.findTransition(function(r){var n,a,i,o,l,s;return n=t,a=r.ev,i=n.seg.start,o=n.seg.end,l=a.seg.start,s=a.seg.end,(e.pointsCollinear(i,l,s)?e.pointsCollinear(o,l,s)?1:e.pointAboveOrOnLine(o,l,s)?1:-1:e.pointAboveOrOnLine(i,l,s)?1:-1)>0})}function u(t,n){var a=t.seg,i=n.seg,o=a.start,l=a.end,c=i.start,u=i.end;r&&r.checkIntersection(a,i);var f=e.linesIntersect(o,l,c,u);if(!1===f){if(!e.pointsCollinear(o,l,c))return!1;if(e.pointsSame(o,u)||e.pointsSame(l,c))return!1;var d=e.pointsSame(o,c),p=e.pointsSame(l,u);if(d&&p)return n;var h=!d&&e.pointBetween(o,c,u),g=!p&&e.pointBetween(l,c,u);if(d)return g?s(n,l):s(t,u),n;h&&(p||(g?s(n,l):s(t,u)),s(n,o))}else 0===f.alongA&&(-1===f.alongB?s(t,c):0===f.alongB?s(t,f.pt):1===f.alongB&&s(t,u)),0===f.alongB&&(-1===f.alongA?s(n,o):0===f.alongA?s(n,f.pt):1===f.alongA&&s(n,l));return!1}for(var f=[];!i.isEmpty();){var d=i.getHead();if(r&&r.vert(d.pt[0]),d.isStart){r&&r.segmentNew(d.seg,d.primary);var p=c(d),h=p.before?p.before.ev:null,g=p.after?p.after.ev:null;function y(){if(h){var t=u(d,h);if(t)return t}return!!g&&u(d,g)}r&&r.tempStatus(d.seg,!!h&&h.seg,!!g&&g.seg);var v,m,x=y();if(x)t?(m=null===d.seg.myFill.below||d.seg.myFill.above!==d.seg.myFill.below)&&(x.seg.myFill.above=!x.seg.myFill.above):x.seg.otherFill=d.seg.myFill,r&&r.segmentUpdate(x.seg),d.other.remove(),d.remove();if(i.getHead()!==d){r&&r.rewind(d.seg);continue}t?(m=null===d.seg.myFill.below||d.seg.myFill.above!==d.seg.myFill.below,d.seg.myFill.below=g?g.seg.myFill.above:a,d.seg.myFill.above=m?!d.seg.myFill.below:d.seg.myFill.below):null===d.seg.otherFill&&(v=g?d.primary===g.primary?g.seg.otherFill.above:g.seg.myFill.above:d.primary?o:a,d.seg.otherFill={above:v,below:v}),r&&r.status(d.seg,!!h&&h.seg,!!g&&g.seg),d.other.status=p.insert(n.node({ev:d}))}else{var b=d.status;if(null===b)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");if(l.exists(b.prev)&&l.exists(b.next)&&u(b.prev.ev,b.next.ev),r&&r.statusRemove(b.ev.seg),b.remove(),!d.primary){var _=d.seg.myFill;d.seg.myFill=d.seg.otherFill,d.seg.otherFill=_}f.push(d.seg)}i.getHead().remove()}return r&&r.done(),f}return t?{addRegion:function(t){for(var n,a,i,o=t[t.length-1],s=0;s<t.length;s++){n=o,o=t[s];var c=e.pointsCompare(n,o);0!==c&&l((a=c<0?n:o,i=c<0?o:n,{id:r?r.segmentId():-1,start:a,end:i,myFill:{above:null,below:null},otherFill:null}),!0)}},calculate:function(t){return c(t,!1)}}:{calculate:function(t,e,r,n){return t.forEach(function(t){l(a(t.start,t.end,t),!0)}),r.forEach(function(t){l(a(t.start,t.end,t),!1)}),c(e,n)}}}},{"./linked-list":24}],24:[function(t,e,r){e.exports={create:function(){var t={root:{root:!0,next:null},exists:function(e){return null!==e&&e!==t.root},isEmpty:function(){return null===t.root.next},getHead:function(){return t.root.next},insertBefore:function(e,r){for(var n=t.root,a=t.root.next;null!==a;){if(r(a))return e.prev=a.prev,e.next=a,a.prev.next=e,void(a.prev=e);n=a,a=a.next}n.next=e,e.prev=n,e.next=null},findTransition:function(e){for(var r=t.root,n=t.root.next;null!==n&&!e(n);)r=n,n=n.next;return{before:r===t.root?null:r,after:n,insert:function(t){return t.prev=r,t.next=n,r.next=t,null!==n&&(n.prev=t),t}}}};return t},node:function(t){return t.prev=null,t.next=null,t.remove=function(){t.prev.next=t.next,t.next&&(t.next.prev=t.prev),t.prev=null,t.next=null},t}}},{}],25:[function(t,e,r){e.exports=function(t,e,r){var n=[],a=[];return t.forEach(function(t){var i=t.start,o=t.end;if(e.pointsSame(i,o))console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large");else{r&&r.chainStart(t);for(var l={index:0,matches_head:!1,matches_pt1:!1},s={index:0,matches_head:!1,matches_pt1:!1},c=l,u=0;u<n.length;u++){var f=(y=n[u])[0],d=(y[1],y[y.length-1]);if(y[y.length-2],e.pointsSame(f,i)){if(M(u,!0,!0))break}else if(e.pointsSame(f,o)){if(M(u,!0,!1))break}else if(e.pointsSame(d,i)){if(M(u,!1,!0))break}else if(e.pointsSame(d,o)&&M(u,!1,!1))break}if(c===l)return n.push([i,o]),void(r&&r.chainNew(i,o));if(c===s){r&&r.chainMatch(l.index);var p=l.index,h=l.matches_pt1?o:i,g=l.matches_head,y=n[p],v=g?y[0]:y[y.length-1],m=g?y[1]:y[y.length-2],x=g?y[y.length-1]:y[0],b=g?y[y.length-2]:y[1];return e.pointsCollinear(m,v,h)&&(g?(r&&r.chainRemoveHead(l.index,h),y.shift()):(r&&r.chainRemoveTail(l.index,h),y.pop()),v=m),e.pointsSame(x,h)?(n.splice(p,1),e.pointsCollinear(b,x,v)&&(g?(r&&r.chainRemoveTail(l.index,v),y.pop()):(r&&r.chainRemoveHead(l.index,v),y.shift())),r&&r.chainClose(l.index),void a.push(y)):void(g?(r&&r.chainAddHead(l.index,h),y.unshift(h)):(r&&r.chainAddTail(l.index,h),y.push(h)))}var _=l.index,w=s.index;r&&r.chainConnect(_,w);var k=n[_].length<n[w].length;l.matches_head?s.matches_head?k?(T(_),A(_,w)):(T(w),A(w,_)):A(w,_):s.matches_head?A(_,w):k?(T(_),A(w,_)):(T(w),A(_,w))}function M(t,e,r){return c.index=t,c.matches_head=e,c.matches_pt1=r,c===l?(c=s,!1):(c=null,!0)}function T(t){r&&r.chainReverse(t),n[t].reverse()}function A(t,a){var i=n[t],o=n[a],l=i[i.length-1],s=i[i.length-2],c=o[0],u=o[1];e.pointsCollinear(s,l,c)&&(r&&r.chainRemoveTail(t,l),i.pop(),l=s),e.pointsCollinear(l,c,u)&&(r&&r.chainRemoveHead(a,c),o.shift()),r&&r.chainJoin(t,a),n[t]=i.concat(o),n.splice(a,1)}}),a}},{}],26:[function(t,e,r){function n(t,e,r){var n=[];return t.forEach(function(t){var a=(t.myFill.above?8:0)+(t.myFill.below?4:0)+(t.otherFill&&t.otherFill.above?2:0)+(t.otherFill&&t.otherFill.below?1:0);0!==e[a]&&n.push({id:r?r.segmentId():-1,start:t.start,end:t.end,myFill:{above:1===e[a],below:2===e[a]},otherFill:null})}),r&&r.selected(n),n}var a={union:function(t,e){return n(t,[0,2,1,0,2,2,0,0,1,0,1,0,0,0,0,0],e)},intersect:function(t,e){return n(t,[0,0,0,0,0,2,0,2,0,0,1,1,0,2,1,0],e)},difference:function(t,e){return n(t,[0,0,0,0,2,0,2,0,1,1,0,0,0,1,2,0],e)},differenceRev:function(t,e){return n(t,[0,2,1,0,0,0,1,1,0,2,0,2,0,0,0,0],e)},xor:function(t,e){return n(t,[0,2,1,0,2,0,0,1,1,0,0,2,0,1,2,0],e)}};e.exports=a},{}],27:[function(t,e,r){var n,a,i=e.exports={};function o(){throw new Error("setTimeout has not been defined")}function l(){throw new Error("clearTimeout has not been defined")}function s(t){if(n===setTimeout)return setTimeout(t,0);if((n===o||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:o}catch(t){n=o}try{a="function"==typeof clearTimeout?clearTimeout:l}catch(t){a=l}}();var c,u=[],f=!1,d=-1;function p(){f&&c&&(f=!1,c.length?u=c.concat(u):d=-1,u.length&&h())}function h(){if(!f){var t=s(p);f=!0;for(var e=u.length;e;){for(c=u,u=[];++d<e;)c&&c[d].run();d=-1,e=u.length}c=null,f=!1,function(t){if(a===clearTimeout)return clearTimeout(t);if((a===l||!a)&&clearTimeout)return a=clearTimeout,clearTimeout(t);try{a(t)}catch(e){try{return a.call(null,t)}catch(e){return a.call(this,t)}}}(t)}}function g(t,e){this.fun=t,this.array=e}function y(){}i.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];u.push(new g(t,e)),1!==u.length||f||s(h)},g.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=y,i.addListener=y,i.once=y,i.off=y,i.removeListener=y,i.removeAllListeners=y,i.emit=y,i.prependListener=y,i.prependOnceListener=y,i.listeners=function(t){return[]},i.binding=function(t){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(t){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],28:[function(t,e,r){!function(t){var r=/^\s+/,n=/\s+$/,a=0,i=t.round,o=t.min,l=t.max,s=t.random;function c(e,s){if(s=s||{},(e=e||"")instanceof c)return e;if(!(this instanceof c))return new c(e,s);var u=function(e){var a={r:0,g:0,b:0},i=1,s=null,c=null,u=null,f=!1,d=!1;"string"==typeof e&&(e=function(t){t=t.replace(r,"").replace(n,"").toLowerCase();var e,a=!1;if(L[t])t=L[t],a=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(e=B.rgb.exec(t))return{r:e[1],g:e[2],b:e[3]};if(e=B.rgba.exec(t))return{r:e[1],g:e[2],b:e[3],a:e[4]};if(e=B.hsl.exec(t))return{h:e[1],s:e[2],l:e[3]};if(e=B.hsla.exec(t))return{h:e[1],s:e[2],l:e[3],a:e[4]};if(e=B.hsv.exec(t))return{h:e[1],s:e[2],v:e[3]};if(e=B.hsva.exec(t))return{h:e[1],s:e[2],v:e[3],a:e[4]};if(e=B.hex8.exec(t))return{r:D(e[1]),g:D(e[2]),b:D(e[3]),a:N(e[4]),format:a?"name":"hex8"};if(e=B.hex6.exec(t))return{r:D(e[1]),g:D(e[2]),b:D(e[3]),format:a?"name":"hex"};if(e=B.hex4.exec(t))return{r:D(e[1]+""+e[1]),g:D(e[2]+""+e[2]),b:D(e[3]+""+e[3]),a:N(e[4]+""+e[4]),format:a?"name":"hex8"};if(e=B.hex3.exec(t))return{r:D(e[1]+""+e[1]),g:D(e[2]+""+e[2]),b:D(e[3]+""+e[3]),format:a?"name":"hex"};return!1}(e));"object"==typeof e&&(H(e.r)&&H(e.g)&&H(e.b)?(p=e.r,h=e.g,g=e.b,a={r:255*O(p,255),g:255*O(h,255),b:255*O(g,255)},f=!0,d="%"===String(e.r).substr(-1)?"prgb":"rgb"):H(e.h)&&H(e.s)&&H(e.v)?(s=E(e.s),c=E(e.v),a=function(e,r,n){e=6*O(e,360),r=O(r,100),n=O(n,100);var a=t.floor(e),i=e-a,o=n*(1-r),l=n*(1-i*r),s=n*(1-(1-i)*r),c=a%6;return{r:255*[n,l,o,o,s,n][c],g:255*[s,n,n,l,o,o][c],b:255*[o,o,s,n,n,l][c]}}(e.h,s,c),f=!0,d="hsv"):H(e.h)&&H(e.s)&&H(e.l)&&(s=E(e.s),u=E(e.l),a=function(t,e,r){var n,a,i;function o(t,e,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?t+6*(e-t)*r:r<.5?e:r<2/3?t+(e-t)*(2/3-r)*6:t}if(t=O(t,360),e=O(e,100),r=O(r,100),0===e)n=a=i=r;else{var l=r<.5?r*(1+e):r+e-r*e,s=2*r-l;n=o(s,l,t+1/3),a=o(s,l,t),i=o(s,l,t-1/3)}return{r:255*n,g:255*a,b:255*i}}(e.h,s,u),f=!0,d="hsl"),e.hasOwnProperty("a")&&(i=e.a));var p,h,g;return i=S(i),{ok:f,format:e.format||d,r:o(255,l(a.r,0)),g:o(255,l(a.g,0)),b:o(255,l(a.b,0)),a:i}}(e);this._originalInput=e,this._r=u.r,this._g=u.g,this._b=u.b,this._a=u.a,this._roundA=i(100*this._a)/100,this._format=s.format||u.format,this._gradientType=s.gradientType,this._r<1&&(this._r=i(this._r)),this._g<1&&(this._g=i(this._g)),this._b<1&&(this._b=i(this._b)),this._ok=u.ok,this._tc_id=a++}function u(t,e,r){t=O(t,255),e=O(e,255),r=O(r,255);var n,a,i=l(t,e,r),s=o(t,e,r),c=(i+s)/2;if(i==s)n=a=0;else{var u=i-s;switch(a=c>.5?u/(2-i-s):u/(i+s),i){case t:n=(e-r)/u+(e<r?6:0);break;case e:n=(r-t)/u+2;break;case r:n=(t-e)/u+4}n/=6}return{h:n,s:a,l:c}}function f(t,e,r){t=O(t,255),e=O(e,255),r=O(r,255);var n,a,i=l(t,e,r),s=o(t,e,r),c=i,u=i-s;if(a=0===i?0:u/i,i==s)n=0;else{switch(i){case t:n=(e-r)/u+(e<r?6:0);break;case e:n=(r-t)/u+2;break;case r:n=(t-e)/u+4}n/=6}return{h:n,s:a,v:c}}function d(t,e,r,n){var a=[z(i(t).toString(16)),z(i(e).toString(16)),z(i(r).toString(16))];return n&&a[0].charAt(0)==a[0].charAt(1)&&a[1].charAt(0)==a[1].charAt(1)&&a[2].charAt(0)==a[2].charAt(1)?a[0].charAt(0)+a[1].charAt(0)+a[2].charAt(0):a.join("")}function p(t,e,r,n){return[z(I(n)),z(i(t).toString(16)),z(i(e).toString(16)),z(i(r).toString(16))].join("")}function h(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.s-=e/100,r.s=P(r.s),c(r)}function g(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.s+=e/100,r.s=P(r.s),c(r)}function y(t){return c(t).desaturate(100)}function v(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.l+=e/100,r.l=P(r.l),c(r)}function m(t,e){e=0===e?0:e||10;var r=c(t).toRgb();return r.r=l(0,o(255,r.r-i(-e/100*255))),r.g=l(0,o(255,r.g-i(-e/100*255))),r.b=l(0,o(255,r.b-i(-e/100*255))),c(r)}function x(t,e){e=0===e?0:e||10;var r=c(t).toHsl();return r.l-=e/100,r.l=P(r.l),c(r)}function b(t,e){var r=c(t).toHsl(),n=(r.h+e)%360;return r.h=n<0?360+n:n,c(r)}function _(t){var e=c(t).toHsl();return e.h=(e.h+180)%360,c(e)}function w(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+120)%360,s:e.s,l:e.l}),c({h:(r+240)%360,s:e.s,l:e.l})]}function k(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+90)%360,s:e.s,l:e.l}),c({h:(r+180)%360,s:e.s,l:e.l}),c({h:(r+270)%360,s:e.s,l:e.l})]}function M(t){var e=c(t).toHsl(),r=e.h;return[c(t),c({h:(r+72)%360,s:e.s,l:e.l}),c({h:(r+216)%360,s:e.s,l:e.l})]}function T(t,e,r){e=e||6,r=r||30;var n=c(t).toHsl(),a=360/r,i=[c(t)];for(n.h=(n.h-(a*e>>1)+720)%360;--e;)n.h=(n.h+a)%360,i.push(c(n));return i}function A(t,e){e=e||6;for(var r=c(t).toHsv(),n=r.h,a=r.s,i=r.v,o=[],l=1/e;e--;)o.push(c({h:n,s:a,v:i})),i=(i+l)%1;return o}c.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var e,r,n,a=this.toRgb();return e=a.r/255,r=a.g/255,n=a.b/255,.2126*(e<=.03928?e/12.92:t.pow((e+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:t.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:t.pow((n+.055)/1.055,2.4))},setAlpha:function(t){return this._a=S(t),this._roundA=i(100*this._a)/100,this},toHsv:function(){var t=f(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=f(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=u(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=u(this._r,this._g,this._b),e=i(360*t.h),r=i(100*t.s),n=i(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return d(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,e,r,n,a){var o=[z(i(t).toString(16)),z(i(e).toString(16)),z(i(r).toString(16)),z(I(n))];if(a&&o[0].charAt(0)==o[0].charAt(1)&&o[1].charAt(0)==o[1].charAt(1)&&o[2].charAt(0)==o[2].charAt(1)&&o[3].charAt(0)==o[3].charAt(1))return o[0].charAt(0)+o[1].charAt(0)+o[2].charAt(0)+o[3].charAt(0);return o.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:i(this._r),g:i(this._g),b:i(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+i(this._r)+", "+i(this._g)+", "+i(this._b)+")":"rgba("+i(this._r)+", "+i(this._g)+", "+i(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:i(100*O(this._r,255))+"%",g:i(100*O(this._g,255))+"%",b:i(100*O(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+i(100*O(this._r,255))+"%, "+i(100*O(this._g,255))+"%, "+i(100*O(this._b,255))+"%)":"rgba("+i(100*O(this._r,255))+"%, "+i(100*O(this._g,255))+"%, "+i(100*O(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(C[d(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var e="#"+p(this._r,this._g,this._b,this._a),r=e,n=this._gradientType?"GradientType = 1, ":"";if(t){var a=c(t);r="#"+p(a._r,a._g,a._b,a._a)}return"progid:DXImageTransform.Microsoft.gradient("+n+"startColorstr="+e+",endColorstr="+r+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0;return e||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex4"===t&&(r=this.toHex8String(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return c(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(v,arguments)},brighten:function(){return this._applyModification(m,arguments)},darken:function(){return this._applyModification(x,arguments)},desaturate:function(){return this._applyModification(h,arguments)},saturate:function(){return this._applyModification(g,arguments)},greyscale:function(){return this._applyModification(y,arguments)},spin:function(){return this._applyModification(b,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(T,arguments)},complement:function(){return this._applyCombination(_,arguments)},monochromatic:function(){return this._applyCombination(A,arguments)},splitcomplement:function(){return this._applyCombination(M,arguments)},triad:function(){return this._applyCombination(w,arguments)},tetrad:function(){return this._applyCombination(k,arguments)}},c.fromRatio=function(t,e){if("object"==typeof t){var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]="a"===n?t[n]:E(t[n]));t=r}return c(t,e)},c.equals=function(t,e){return!(!t||!e)&&c(t).toRgbString()==c(e).toRgbString()},c.random=function(){return c.fromRatio({r:s(),g:s(),b:s()})},c.mix=function(t,e,r){r=0===r?0:r||50;var n=c(t).toRgb(),a=c(e).toRgb(),i=r/100;return c({r:(a.r-n.r)*i+n.r,g:(a.g-n.g)*i+n.g,b:(a.b-n.b)*i+n.b,a:(a.a-n.a)*i+n.a})},c.readability=function(e,r){var n=c(e),a=c(r);return(t.max(n.getLuminance(),a.getLuminance())+.05)/(t.min(n.getLuminance(),a.getLuminance())+.05)},c.isReadable=function(t,e,r){var n,a,i=c.readability(t,e);switch(a=!1,(n=function(t){var e,r;e=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA");"small"!==r&&"large"!==r&&(r="small");return{level:e,size:r}}(r)).level+n.size){case"AAsmall":case"AAAlarge":a=i>=4.5;break;case"AAlarge":a=i>=3;break;case"AAAsmall":a=i>=7}return a},c.mostReadable=function(t,e,r){var n,a,i,o,l=null,s=0;a=(r=r||{}).includeFallbackColors,i=r.level,o=r.size;for(var u=0;u<e.length;u++)(n=c.readability(t,e[u]))>s&&(s=n,l=c(e[u]));return c.isReadable(t,l,{level:i,size:o})||!a?l:(r.includeFallbackColors=!1,c.mostReadable(t,["#fff","#000"],r))};var L=c.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},C=c.hexNames=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}(L);function S(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function O(e,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(e)&&(e="100%");var n=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(e);return e=o(r,l(0,parseFloat(e))),n&&(e=parseInt(e*r,10)/100),t.abs(e-r)<1e-6?1:e%r/parseFloat(r)}function P(t){return o(1,l(0,t))}function D(t){return parseInt(t,16)}function z(t){return 1==t.length?"0"+t:""+t}function E(t){return t<=1&&(t=100*t+"%"),t}function I(e){return t.round(255*parseFloat(e)).toString(16)}function N(t){return D(t)/255}var R,F,j,B=(F="[\\s|\\(]+("+(R="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",j="[\\s|\\(]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")[,|\\s]+("+R+")\\s*\\)?",{CSS_UNIT:new RegExp(R),rgb:new RegExp("rgb"+F),rgba:new RegExp("rgba"+j),hsl:new RegExp("hsl"+F),hsla:new RegExp("hsla"+j),hsv:new RegExp("hsv"+F),hsva:new RegExp("hsva"+j),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function H(t){return!!B.CSS_UNIT.exec(t)}"undefined"!=typeof e&&e.exports?e.exports=c:window.tinycolor=c}(Math)},{}],29:[function(t,e,r){"use strict";e.exports=[{path:"",backoff:0},{path:"M-2.4,-3V3L0.6,0Z",backoff:.6},{path:"M-3.7,-2.5V2.5L1.3,0Z",backoff:1.3},{path:"M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z",backoff:1.55},{path:"M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z",backoff:1.6},{path:"M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z",backoff:2},{path:"M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z",backoff:0,noRotate:!0},{path:"M2,2V-2H-2V2Z",backoff:0,noRotate:!0}]},{}],30:[function(t,e,r){"use strict";var n=t("./arrow_paths"),a=t("../../plots/font_attributes"),i=t("../../plots/cartesian/constants"),o=t("../../plot_api/plot_template").templatedArray;e.exports=o("annotation",{visible:{valType:"boolean",dflt:!0,editType:"calcIfAutorange+arraydraw"},text:{valType:"string",editType:"calcIfAutorange+arraydraw"},textangle:{valType:"angle",dflt:0,editType:"calcIfAutorange+arraydraw"},font:a({editType:"calcIfAutorange+arraydraw",colorEditType:"arraydraw"}),width:{valType:"number",min:1,dflt:null,editType:"calcIfAutorange+arraydraw"},height:{valType:"number",min:1,dflt:null,editType:"calcIfAutorange+arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},align:{valType:"enumerated",values:["left","center","right"],dflt:"center",editType:"arraydraw"},valign:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle",editType:"arraydraw"},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},bordercolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},borderpad:{valType:"number",min:0,dflt:1,editType:"calcIfAutorange+arraydraw"},borderwidth:{valType:"number",min:0,dflt:1,editType:"calcIfAutorange+arraydraw"},showarrow:{valType:"boolean",dflt:!0,editType:"calcIfAutorange+arraydraw"},arrowcolor:{valType:"color",editType:"arraydraw"},arrowhead:{valType:"integer",min:0,max:n.length,dflt:1,editType:"arraydraw"},startarrowhead:{valType:"integer",min:0,max:n.length,dflt:1,editType:"arraydraw"},arrowside:{valType:"flaglist",flags:["end","start"],extras:["none"],dflt:"end",editType:"arraydraw"},arrowsize:{valType:"number",min:.3,dflt:1,editType:"calcIfAutorange+arraydraw"},startarrowsize:{valType:"number",min:.3,dflt:1,editType:"calcIfAutorange+arraydraw"},arrowwidth:{valType:"number",min:.1,editType:"calcIfAutorange+arraydraw"},standoff:{valType:"number",min:0,dflt:0,editType:"calcIfAutorange+arraydraw"},startstandoff:{valType:"number",min:0,dflt:0,editType:"calcIfAutorange+arraydraw"},ax:{valType:"any",editType:"calcIfAutorange+arraydraw"},ay:{valType:"any",editType:"calcIfAutorange+arraydraw"},axref:{valType:"enumerated",dflt:"pixel",values:["pixel",i.idRegex.x.toString()],editType:"calc"},ayref:{valType:"enumerated",dflt:"pixel",values:["pixel",i.idRegex.y.toString()],editType:"calc"},xref:{valType:"enumerated",values:["paper",i.idRegex.x.toString()],editType:"calc"},x:{valType:"any",editType:"calcIfAutorange+arraydraw"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"auto",editType:"calcIfAutorange+arraydraw"},xshift:{valType:"number",dflt:0,editType:"calcIfAutorange+arraydraw"},yref:{valType:"enumerated",values:["paper",i.idRegex.y.toString()],editType:"calc"},y:{valType:"any",editType:"calcIfAutorange+arraydraw"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"calcIfAutorange+arraydraw"},yshift:{valType:"number",dflt:0,editType:"calcIfAutorange+arraydraw"},clicktoshow:{valType:"enumerated",values:[!1,"onoff","onout"],dflt:!1,editType:"arraydraw"},xclick:{valType:"any",editType:"arraydraw"},yclick:{valType:"any",editType:"arraydraw"},hovertext:{valType:"string",editType:"arraydraw"},hoverlabel:{bgcolor:{valType:"color",editType:"arraydraw"},bordercolor:{valType:"color",editType:"arraydraw"},font:a({editType:"arraydraw"}),editType:"arraydraw"},captureevents:{valType:"boolean",editType:"arraydraw"},editType:"calc",_deprecated:{ref:{valType:"string",editType:"calc"}}})},{"../../plot_api/plot_template":197,"../../plots/cartesian/constants":212,"../../plots/font_attributes":233,"./arrow_paths":29}],31:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("./draw").draw;function o(t){var e=t._fullLayout;n.filterVisible(e.annotations).forEach(function(e){var r,n,i,o,l=a.getFromId(t,e.xref),s=a.getFromId(t,e.yref),c=3*e.arrowsize*e.arrowwidth||0,u=3*e.startarrowsize*e.arrowwidth||0;l&&l.autorange&&(r=c+e.xshift,n=c-e.xshift,i=u+e.xshift,o=u-e.xshift,e.axref===e.xref?(a.expand(l,[l.r2c(e.x)],{ppadplus:r,ppadminus:n}),a.expand(l,[l.r2c(e.ax)],{ppadplus:Math.max(e._xpadplus,i),ppadminus:Math.max(e._xpadminus,o)})):(i=e.ax?i+e.ax:i,o=e.ax?o-e.ax:o,a.expand(l,[l.r2c(e.x)],{ppadplus:Math.max(e._xpadplus,r,i),ppadminus:Math.max(e._xpadminus,n,o)}))),s&&s.autorange&&(r=c-e.yshift,n=c+e.yshift,i=u-e.yshift,o=u+e.yshift,e.ayref===e.yref?(a.expand(s,[s.r2c(e.y)],{ppadplus:r,ppadminus:n}),a.expand(s,[s.r2c(e.ay)],{ppadplus:Math.max(e._ypadplus,i),ppadminus:Math.max(e._ypadminus,o)})):(i=e.ay?i+e.ay:i,o=e.ay?o-e.ay:o,a.expand(s,[s.r2c(e.y)],{ppadplus:Math.max(e._ypadplus,r,i),ppadminus:Math.max(e._ypadminus,n,o)})))})}e.exports=function(t){var e=t._fullLayout,r=n.filterVisible(e.annotations);if(r.length&&t._fullData.length){var l={};for(var s in r.forEach(function(t){l[t.xref]=1,l[t.yref]=1}),l){var c=a.getFromId(t,s);if(c&&c.autorange)return n.syncOrAsync([i,o],t)}}}},{"../../lib":163,"../../plots/cartesian/axes":207,"./draw":36}],32:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../registry"),i=t("../../plot_api/plot_template").arrayEditor;function o(t,e){var r,n,a,i,o,s,c,u=t._fullLayout.annotations,f=[],d=[],p=[],h=(e||[]).length;for(r=0;r<u.length;r++)if(i=(a=u[r]).clicktoshow){for(n=0;n<h;n++)if(s=(o=e[n]).xaxis,c=o.yaxis,s._id===a.xref&&c._id===a.yref&&s.d2r(o.x)===l(a._xclick,s)&&c.d2r(o.y)===l(a._yclick,c)){(a.visible?"onout"===i?d:p:f).push(r);break}n===h&&a.visible&&"onout"===i&&d.push(r)}return{on:f,off:d,explicitOff:p}}function l(t,e){return"log"===e.type?e.l2r(t):e.d2r(t)}e.exports={hasClickToShow:function(t,e){var r=o(t,e);return r.on.length>0||r.explicitOff.length>0},onClick:function(t,e){var r,l,s=o(t,e),c=s.on,u=s.off.concat(s.explicitOff),f={},d=t._fullLayout.annotations;if(!c.length&&!u.length)return;for(r=0;r<c.length;r++)(l=i(t.layout,"annotations",d[c[r]])).modifyItem("visible",!0),n.extendFlat(f,l.getUpdateObj());for(r=0;r<u.length;r++)(l=i(t.layout,"annotations",d[u[r]])).modifyItem("visible",!1),n.extendFlat(f,l.getUpdateObj());return a.call("update",t,{},f)}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../registry":247}],33:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../color");e.exports=function(t,e,r,i){i("opacity");var o=i("bgcolor"),l=i("bordercolor"),s=a.opacity(l);i("borderpad");var c=i("borderwidth"),u=i("showarrow");if(i("text",u?" ":r._dfltTitle.annotation),i("textangle"),n.coerceFont(i,"font",r.font),i("width"),i("align"),i("height")&&i("valign"),u){var f,d,p=i("arrowside");-1!==p.indexOf("end")&&(f=i("arrowhead"),d=i("arrowsize")),-1!==p.indexOf("start")&&(i("startarrowhead",f),i("startarrowsize",d)),i("arrowcolor",s?e.bordercolor:a.defaultLine),i("arrowwidth",2*(s&&c||1)),i("standoff"),i("startstandoff")}var h=i("hovertext"),g=r.hoverlabel||{};if(h){var y=i("hoverlabel.bgcolor",g.bgcolor||(a.opacity(o)?a.rgb(o):a.defaultLine)),v=i("hoverlabel.bordercolor",g.bordercolor||a.contrast(y));n.coerceFont(i,"hoverlabel.font",{family:g.font.family,size:g.font.size,color:g.font.color||v})}i("captureevents",!!h)}},{"../../lib":163,"../color":45}],34:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib/to_log_range");e.exports=function(t,e,r,i){e=e||{};var o="log"===r&&"linear"===e.type,l="linear"===r&&"log"===e.type;if(o||l)for(var s,c,u=t._fullLayout.annotations,f=e._id.charAt(0),d=0;d<u.length;d++)s=u[d],c="annotations["+d+"].",s[f+"ref"]===e._id&&p(f),s["a"+f+"ref"]===e._id&&p("a"+f);function p(t){var r=s[t],l=null;l=o?a(r,e.range):Math.pow(10,r),n(l)||(l=null),i(c+t,l)}}},{"../../lib/to_log_range":186,"fast-isnumeric":13}],35:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../../plots/array_container_defaults"),o=t("./common_defaults"),l=t("./attributes");function s(t,e,r){function i(r,a){return n.coerce(t,e,l,r,a)}var s=i("visible"),c=i("clicktoshow");if(s||c){o(t,e,r,i);for(var u=e.showarrow,f=["x","y"],d=[-10,-30],p={_fullLayout:r},h=0;h<2;h++){var g=f[h],y=a.coerceRef(t,e,p,g,"","paper");if(a.coercePosition(e,p,i,y,g,.5),u){var v="a"+g,m=a.coerceRef(t,e,p,v,"pixel");"pixel"!==m&&m!==y&&(m=e[v]="pixel");var x="pixel"===m?d[h]:.4;a.coercePosition(e,p,i,m,v,x)}i(g+"anchor"),i(g+"shift")}if(n.noneOrAll(t,e,["x","y"]),u&&n.noneOrAll(t,e,["ax","ay"]),c){var b=i("xclick"),_=i("yclick");e._xclick=void 0===b?e.x:a.cleanPosition(b,p,e.xref),e._yclick=void 0===_?e.y:a.cleanPosition(_,p,e.yref)}}}e.exports=function(t,e){i(t,e,{name:"annotations",handleItemDefaults:s})}},{"../../lib":163,"../../plots/array_container_defaults":203,"../../plots/cartesian/axes":207,"./attributes":30,"./common_defaults":33}],36:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../plots/plots"),o=t("../../lib"),l=t("../../plots/cartesian/axes"),s=t("../color"),c=t("../drawing"),u=t("../fx"),f=t("../../lib/svg_text_utils"),d=t("../../lib/setcursor"),p=t("../dragelement"),h=t("../../plot_api/plot_template").arrayEditor,g=t("./draw_arrow_head");function y(t,e){var r=t._fullLayout.annotations[e]||{};v(t,r,e,!1,l.getFromId(t,r.xref),l.getFromId(t,r.yref))}function v(t,e,r,i,l,y){var v,m,x=t._fullLayout,b=t._fullLayout._size,_=t._context.edits;i?(v="annotation-"+i,m=i+".annotations"):(v="annotation",m="annotations");var w=h(t.layout,m,e),k=w.modifyBase,M=w.modifyItem,T=w.getUpdateObj;x._infolayer.selectAll("."+v+'[data-index="'+r+'"]').remove();var A="clip"+x._uid+"_ann"+r;if(e._input&&!1!==e.visible){var L={x:{},y:{}},C=+e.textangle||0,S=x._infolayer.append("g").classed(v,!0).attr("data-index",String(r)).style("opacity",e.opacity),O=S.append("g").classed("annotation-text-g",!0),P=_[e.showarrow?"annotationTail":"annotationPosition"],D=e.captureevents||_.annotationText||P,z=O.append("g").style("pointer-events",D?"all":null).call(d,"pointer").on("click",function(){t._dragging=!1;var a={index:r,annotation:e._input,fullAnnotation:e,event:n.event};i&&(a.subplotId=i),t.emit("plotly_clickannotation",a)});e.hovertext&&z.on("mouseover",function(){var r=e.hoverlabel,n=r.font,a=this.getBoundingClientRect(),i=t.getBoundingClientRect();u.loneHover({x0:a.left-i.left,x1:a.right-i.left,y:(a.top+a.bottom)/2-i.top,text:e.hovertext,color:r.bgcolor,borderColor:r.bordercolor,fontFamily:n.family,fontSize:n.size,fontColor:n.color},{container:x._hoverlayer.node(),outerContainer:x._paper.node(),gd:t})}).on("mouseout",function(){u.loneUnhover(x._hoverlayer.node())});var E=e.borderwidth,I=e.borderpad,N=E+I,R=z.append("rect").attr("class","bg").style("stroke-width",E+"px").call(s.stroke,e.bordercolor).call(s.fill,e.bgcolor),F=e.width||e.height,j=x._topclips.selectAll("#"+A).data(F?[0]:[]);j.enter().append("clipPath").classed("annclip",!0).attr("id",A).append("rect"),j.exit().remove();var B=e.font,H=z.append("text").classed("annotation-text",!0).text(e.text);_.annotationText?H.call(f.makeEditable,{delegate:z,gd:t}).call(q).on("edit",function(r){e.text=r,this.call(q),M("text",r),l&&l.autorange&&k(l._name+".autorange",!0),y&&y.autorange&&k(y._name+".autorange",!0),a.call("relayout",t,T())}):H.call(q)}else n.selectAll("#"+A).remove();function q(r){return r.call(c.font,B).attr({"text-anchor":{left:"start",right:"end"}[e.align]||"middle"}),f.convertToTspans(r,t,V),r}function V(){var r=H.selectAll("a");1===r.size()&&r.text()===H.text()&&z.insert("a",":first-child").attr({"xlink:xlink:href":r.attr("xlink:href"),"xlink:xlink:show":r.attr("xlink:show")}).style({cursor:"pointer"}).node().appendChild(R.node());var n=z.select(".annotation-text-math-group"),u=!n.empty(),h=c.bBox((u?n:H).node()),v=h.width,m=h.height,w=e.width||v,D=e.height||m,I=Math.round(w+2*N),B=Math.round(D+2*N);function q(t,e){return"auto"===e&&(e=t<1/3?"left":t>2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}e._w=w,e._h=D;for(var V=!1,U=["x","y"],G=0;G<U.length;G++){var Y,X,Z,W,Q,J=U[G],$=e[J+"ref"]||J,K=e["a"+J+"ref"],tt={x:l,y:y}[J],et=(C+("x"===J?0:-90))*Math.PI/180,rt=I*Math.cos(et),nt=B*Math.sin(et),at=Math.abs(rt)+Math.abs(nt),it=e[J+"anchor"],ot=e[J+"shift"]*("x"===J?1:-1),lt=L[J];if(tt){var st=tt.r2fraction(e[J]);if((t._dragging||!tt.autorange)&&(st<0||st>1)&&(K===$?((st=tt.r2fraction(e["a"+J]))<0||st>1)&&(V=!0):V=!0,V))continue;Y=tt._offset+tt.r2p(e[J]),W=.5}else"x"===J?(Z=e[J],Y=b.l+b.w*Z):(Z=1-e[J],Y=b.t+b.h*Z),W=e.showarrow?.5:Z;if(e.showarrow){lt.head=Y;var ct=e["a"+J];Q=rt*q(.5,e.xanchor)-nt*q(.5,e.yanchor),K===$?(lt.tail=tt._offset+tt.r2p(ct),X=Q):(lt.tail=Y+ct,X=Q+ct),lt.text=lt.tail+Q;var ut=x["x"===J?"width":"height"];if("paper"===$&&(lt.head=o.constrain(lt.head,1,ut-1)),"pixel"===K){var ft=-Math.max(lt.tail-3,lt.text),dt=Math.min(lt.tail+3,lt.text)-ut;ft>0?(lt.tail+=ft,lt.text+=ft):dt>0&&(lt.tail-=dt,lt.text-=dt)}lt.tail+=ot,lt.head+=ot}else X=Q=at*q(W,it),lt.text=Y+Q;lt.text+=ot,Q+=ot,X+=ot,e["_"+J+"padplus"]=at/2+X,e["_"+J+"padminus"]=at/2-X,e["_"+J+"size"]=at,e["_"+J+"shift"]=Q}if(V)z.remove();else{var pt=0,ht=0;if("left"!==e.align&&(pt=(w-v)*("center"===e.align?.5:1)),"top"!==e.valign&&(ht=(D-m)*("middle"===e.valign?.5:1)),u)n.select("svg").attr({x:N+pt-1,y:N+ht}).call(c.setClipUrl,F?A:null);else{var gt=N+ht-h.top,yt=N+pt-h.left;H.call(f.positionText,yt,gt).call(c.setClipUrl,F?A:null)}j.select("rect").call(c.setRect,N,N,w,D),R.call(c.setRect,E/2,E/2,I-E,B-E),z.call(c.setTranslate,Math.round(L.x.text-I/2),Math.round(L.y.text-B/2)),O.attr({transform:"rotate("+C+","+L.x.text+","+L.y.text+")"});var vt,mt=function(r,n){S.selectAll(".annotation-arrow-g").remove();var u=L.x.head,f=L.y.head,d=L.x.tail+r,h=L.y.tail+n,v=L.x.text+r,m=L.y.text+n,x=o.rotationXYMatrix(C,v,m),w=o.apply2DTransform(x),A=o.apply2DTransform2(x),P=+R.attr("width"),D=+R.attr("height"),E=v-.5*P,I=E+P,N=m-.5*D,F=N+D,j=[[E,N,E,F],[E,F,I,F],[I,F,I,N],[I,N,E,N]].map(A);if(!j.reduce(function(t,e){return t^!!o.segmentsIntersect(u,f,u+1e6,f+1e6,e[0],e[1],e[2],e[3])},!1)){j.forEach(function(t){var e=o.segmentsIntersect(d,h,u,f,t[0],t[1],t[2],t[3]);e&&(d=e.x,h=e.y)});var B=e.arrowwidth,H=e.arrowcolor,q=e.arrowside,V=S.append("g").style({opacity:s.opacity(H)}).classed("annotation-arrow-g",!0),U=V.append("path").attr("d","M"+d+","+h+"L"+u+","+f).style("stroke-width",B+"px").call(s.stroke,s.rgb(H));if(g(U,q,e),_.annotationPosition&&U.node().parentNode&&!i){var G=u,Y=f;if(e.standoff){var X=Math.sqrt(Math.pow(u-d,2)+Math.pow(f-h,2));G+=e.standoff*(d-u)/X,Y+=e.standoff*(h-f)/X}var Z,W,Q=V.append("path").classed("annotation-arrow",!0).classed("anndrag",!0).classed("cursor-move",!0).attr({d:"M3,3H-3V-3H3ZM0,0L"+(d-G)+","+(h-Y),transform:"translate("+G+","+Y+")"}).style("stroke-width",B+6+"px").call(s.stroke,"rgba(0,0,0,0)").call(s.fill,"rgba(0,0,0,0)");p.init({element:Q.node(),gd:t,prepFn:function(){var t=c.getTranslate(z);Z=t.x,W=t.y,l&&l.autorange&&k(l._name+".autorange",!0),y&&y.autorange&&k(y._name+".autorange",!0)},moveFn:function(t,r){var n=w(Z,W),a=n[0]+t,i=n[1]+r;z.call(c.setTranslate,a,i),M("x",l?l.p2r(l.r2p(e.x)+t):e.x+t/b.w),M("y",y?y.p2r(y.r2p(e.y)+r):e.y-r/b.h),e.axref===e.xref&&M("ax",l.p2r(l.r2p(e.ax)+t)),e.ayref===e.yref&&M("ay",y.p2r(y.r2p(e.ay)+r)),V.attr("transform","translate("+t+","+r+")"),O.attr({transform:"rotate("+C+","+a+","+i+")"})},doneFn:function(){a.call("relayout",t,T());var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}};if(e.showarrow&&mt(0,0),P)p.init({element:z.node(),gd:t,prepFn:function(){vt=O.attr("transform")},moveFn:function(t,r){var n="pointer";if(e.showarrow)e.axref===e.xref?M("ax",l.p2r(l.r2p(e.ax)+t)):M("ax",e.ax+t),e.ayref===e.yref?M("ay",y.p2r(y.r2p(e.ay)+r)):M("ay",e.ay+r),mt(t,r);else{if(i)return;var a,o;if(l)a=l.p2r(l.r2p(e.x)+t);else{var s=e._xsize/b.w,c=e.x+(e._xshift-e.xshift)/b.w-s/2;a=p.align(c+t/b.w,s,0,1,e.xanchor)}if(y)o=y.p2r(y.r2p(e.y)+r);else{var u=e._ysize/b.h,f=e.y-(e._yshift+e.yshift)/b.h-u/2;o=p.align(f-r/b.h,u,0,1,e.yanchor)}M("x",a),M("y",o),l&&y||(n=p.getCursor(l?.5:a,y?.5:o,e.xanchor,e.yanchor))}O.attr({transform:"translate("+t+","+r+")"+vt}),d(z,n)},doneFn:function(){d(z),a.call("relayout",t,T());var e=document.querySelector(".js-notes-box-panel");e&&e.redraw(e.selectedObj)}})}}}e.exports={draw:function(t){var e=t._fullLayout;e._infolayer.selectAll(".annotation").remove();for(var r=0;r<e.annotations.length;r++)e.annotations[r].visible&&y(t,r);return i.previousPromises(t)},drawOne:y,drawRaw:v}},{"../../lib":163,"../../lib/setcursor":182,"../../lib/svg_text_utils":184,"../../plot_api/plot_template":197,"../../plots/cartesian/axes":207,"../../plots/plots":239,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"../fx":87,"./draw_arrow_head":37,d3:10}],37:[function(t,e,r){"use strict";var n=t("d3"),a=t("../color"),i=t("./arrow_paths");e.exports=function(t,e,r){var o,l,s,c,u=t.node(),f=i[r.arrowhead||0],d=i[r.startarrowhead||0],p=(r.arrowwidth||1)*(r.arrowsize||1),h=(r.arrowwidth||1)*(r.startarrowsize||1),g=e.indexOf("start")>=0,y=e.indexOf("end")>=0,v=f.backoff*p+r.standoff,m=d.backoff*h+r.startstandoff;if("line"===u.nodeName){o={x:+t.attr("x1"),y:+t.attr("y1")},l={x:+t.attr("x2"),y:+t.attr("y2")};var x=o.x-l.x,b=o.y-l.y;if(c=(s=Math.atan2(b,x))+Math.PI,v&&m&&v+m>Math.sqrt(x*x+b*b))return void P();if(v){if(v*v>x*x+b*b)return void P();var _=v*Math.cos(s),w=v*Math.sin(s);l.x+=_,l.y+=w,t.attr({x2:l.x,y2:l.y})}if(m){if(m*m>x*x+b*b)return void P();var k=m*Math.cos(s),M=m*Math.sin(s);o.x-=k,o.y-=M,t.attr({x1:o.x,y1:o.y})}}else if("path"===u.nodeName){var T=u.getTotalLength(),A="";if(T<v+m)return void P();var L=u.getPointAtLength(0),C=u.getPointAtLength(.1);s=Math.atan2(L.y-C.y,L.x-C.x),o=u.getPointAtLength(Math.min(m,T)),A="0px,"+m+"px,";var S=u.getPointAtLength(T),O=u.getPointAtLength(T-.1);c=Math.atan2(S.y-O.y,S.x-O.x),l=u.getPointAtLength(Math.max(0,T-v)),A+=T-(A?m+v:v)+"px,"+T+"px",t.style("stroke-dasharray",A)}function P(){t.style("stroke-dasharray","0px,100px")}function D(e,i,o,l){e.path&&(e.noRotate&&(o=0),n.select(u.parentNode).append("path").attr({class:t.attr("class"),d:e.path,transform:"translate("+i.x+","+i.y+")"+(o?"rotate("+180*o/Math.PI+")":"")+"scale("+l+")"}).style({fill:a.rgb(r.arrowcolor),"stroke-width":0}))}g&&D(d,o,s,h),y&&D(f,l,c,p)}},{"../color":45,"./arrow_paths":29,d3:10}],38:[function(t,e,r){"use strict";var n=t("./draw"),a=t("./click");e.exports={moduleType:"component",name:"annotations",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("annotations"),calcAutorange:t("./calc_autorange"),draw:n.draw,drawOne:n.drawOne,drawRaw:n.drawRaw,hasClickToShow:a.hasClickToShow,onClick:a.onClick,convertCoords:t("./convert_coords")}},{"../../plots/cartesian/include_components":217,"./attributes":30,"./calc_autorange":31,"./click":32,"./convert_coords":34,"./defaults":35,"./draw":36}],39:[function(t,e,r){"use strict";var n=t("../annotations/attributes"),a=t("../../plot_api/edit_types").overrideAll,i=t("../../plot_api/plot_template").templatedArray;e.exports=a(i("annotation",{visible:n.visible,x:{valType:"any"},y:{valType:"any"},z:{valType:"any"},ax:{valType:"number"},ay:{valType:"number"},xanchor:n.xanchor,xshift:n.xshift,yanchor:n.yanchor,yshift:n.yshift,text:n.text,textangle:n.textangle,font:n.font,width:n.width,height:n.height,opacity:n.opacity,align:n.align,valign:n.valign,bgcolor:n.bgcolor,bordercolor:n.bordercolor,borderpad:n.borderpad,borderwidth:n.borderwidth,showarrow:n.showarrow,arrowcolor:n.arrowcolor,arrowhead:n.arrowhead,startarrowhead:n.startarrowhead,arrowside:n.arrowside,arrowsize:n.arrowsize,startarrowsize:n.startarrowsize,arrowwidth:n.arrowwidth,standoff:n.standoff,startstandoff:n.startstandoff,hovertext:n.hovertext,hoverlabel:n.hoverlabel,captureevents:n.captureevents}),"calc","from-root")},{"../../plot_api/edit_types":190,"../../plot_api/plot_template":197,"../annotations/attributes":30}],40:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes");function i(t,e){var r=e.fullSceneLayout.domain,i=e.fullLayout._size,o={pdata:null,type:"linear",autorange:!1,range:[-1/0,1/0]};t._xa={},n.extendFlat(t._xa,o),a.setConvert(t._xa),t._xa._offset=i.l+r.x[0]*i.w,t._xa.l2p=function(){return.5*(1+t._pdata[0]/t._pdata[3])*i.w*(r.x[1]-r.x[0])},t._ya={},n.extendFlat(t._ya,o),a.setConvert(t._ya),t._ya._offset=i.t+(1-r.y[1])*i.h,t._ya.l2p=function(){return.5*(1-t._pdata[1]/t._pdata[3])*i.h*(r.y[1]-r.y[0])}}e.exports=function(t){for(var e=t.fullSceneLayout.annotations,r=0;r<e.length;r++)i(e[r],t);t.fullLayout._infolayer.selectAll(".annotation-"+t.id).remove()}},{"../../lib":163,"../../plots/cartesian/axes":207}],41:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../../plots/array_container_defaults"),o=t("../annotations/common_defaults"),l=t("./attributes");function s(t,e,r,i){function s(r,a){return n.coerce(t,e,l,r,a)}function c(t){var n=t+"axis",i={_fullLayout:{}};return i._fullLayout[n]=r[n],a.coercePosition(e,i,s,t,t,.5)}s("visible")&&(o(t,e,i.fullLayout,s),c("x"),c("y"),c("z"),n.noneOrAll(t,e,["x","y","z"]),e.xref="x",e.yref="y",e.zref="z",s("xanchor"),s("yanchor"),s("xshift"),s("yshift"),e.showarrow&&(e.axref="pixel",e.ayref="pixel",s("ax",-10),s("ay",-30),n.noneOrAll(t,e,["ax","ay"])))}e.exports=function(t,e,r){i(t,e,{name:"annotations",handleItemDefaults:s,fullLayout:r.fullLayout})}},{"../../lib":163,"../../plots/array_container_defaults":203,"../../plots/cartesian/axes":207,"../annotations/common_defaults":33,"./attributes":39}],42:[function(t,e,r){"use strict";var n=t("../annotations/draw").drawRaw,a=t("../../plots/gl3d/project"),i=["x","y","z"];e.exports=function(t){for(var e=t.fullSceneLayout,r=t.dataScale,o=e.annotations,l=0;l<o.length;l++){for(var s=o[l],c=!1,u=0;u<3;u++){var f=i[u],d=s[f],p=e[f+"axis"].r2fraction(d);if(p<0||p>1){c=!0;break}}c?t.fullLayout._infolayer.select(".annotation-"+t.id+'[data-index="'+l+'"]').remove():(s._pdata=a(t.glplot.cameraParams,[e.xaxis.r2l(s.x)*r[0],e.yaxis.r2l(s.y)*r[1],e.zaxis.r2l(s.z)*r[2]]),n(t.graphDiv,s,l,t.id,s._xa,s._ya))}}},{"../../plots/gl3d/project":236,"../annotations/draw":36}],43:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib");e.exports={moduleType:"component",name:"annotations3d",schema:{subplots:{scene:{annotations:t("./attributes")}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),includeBasePlot:function(t,e){var r=n.subplotsRegistry.gl3d;if(!r)return;for(var i=r.attrRegex,o=Object.keys(t),l=0;l<o.length;l++){var s=o[l];i.test(s)&&(t[s].annotations||[]).length&&(a.pushUnique(e._basePlotModules,r),a.pushUnique(e._subplots.gl3d,s))}},convert:t("./convert"),draw:t("./draw")}},{"../../lib":163,"../../registry":247,"./attributes":39,"./convert":40,"./defaults":41,"./draw":42}],44:[function(t,e,r){"use strict";r.defaults=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],r.defaultLine="#444",r.lightLine="#eee",r.background="#fff",r.borderLine="#BEC8D9",r.lightFraction=1e3/11},{}],45:[function(t,e,r){"use strict";var n=t("tinycolor2"),a=t("fast-isnumeric"),i=e.exports={},o=t("./attributes");i.defaults=o.defaults;var l=i.defaultLine=o.defaultLine;i.lightLine=o.lightLine;var s=i.background=o.background;function c(t){if(a(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),i="a"===e.charAt(3)&&4===n.length;if(!i&&3!==n.length)return t;for(var o=0;o<n.length;o++){if(!n[o].length)return t;if(n[o]=Number(n[o]),!(n[o]>=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var l=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+l+", "+n[3]+")":"rgb("+l+")"}i.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},i.rgb=function(t){return i.tinyRGB(n(t))},i.opacity=function(t){return t?n(t).getAlpha():0},i.addOpacity=function(t,e){var r=n(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},i.combine=function(t,e){var r=n(t).toRgb();if(1===r.a)return n(t).toRgbString();var a=n(e||s).toRgb(),i=1===a.a?a:{r:255*(1-a.a)+a.r*a.a,g:255*(1-a.a)+a.g*a.a,b:255*(1-a.a)+a.b*a.a},o={r:i.r*(1-r.a)+r.r*r.a,g:i.g*(1-r.a)+r.g*r.a,b:i.b*(1-r.a)+r.b*r.a};return n(o).toRgbString()},i.contrast=function(t,e,r){var a=n(t);return 1!==a.getAlpha()&&(a=n(i.combine(t,s))),(a.isDark()?e?a.lighten(e):s:r?a.darken(r):l).toString()},i.stroke=function(t,e){var r=n(e);t.style({stroke:i.tinyRGB(r),"stroke-opacity":r.getAlpha()})},i.fill=function(t,e){var r=n(e);t.style({fill:i.tinyRGB(r),"fill-opacity":r.getAlpha()})},i.clean=function(t){if(t&&"object"==typeof t){var e,r,n,a,o=Object.keys(t);for(e=0;e<o.length;e++)if(a=t[n=o[e]],"color"===n.substr(n.length-5))if(Array.isArray(a))for(r=0;r<a.length;r++)a[r]=c(a[r]);else t[n]=c(a);else if("colorscale"===n.substr(n.length-10)&&Array.isArray(a))for(r=0;r<a.length;r++)Array.isArray(a[r])&&(a[r][1]=c(a[r][1]));else if(Array.isArray(a)){var l=a[0];if(!Array.isArray(l)&&l&&"object"==typeof l)for(r=0;r<a.length;r++)i.clean(a[r])}else a&&"object"==typeof a&&i.clean(a)}}},{"./attributes":44,"fast-isnumeric":13,tinycolor2:28}],46:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/layout_attributes"),a=t("../../plots/font_attributes"),i=t("../../lib/extend").extendFlat,o=t("../../plot_api/edit_types").overrideAll;e.exports=o({thicknessmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"pixels"},thickness:{valType:"number",min:0,dflt:30},lenmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"fraction"},len:{valType:"number",min:0,dflt:1},x:{valType:"number",dflt:1.02,min:-2,max:3},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},xpad:{valType:"number",min:0,dflt:10},y:{valType:"number",dflt:.5,min:-2,max:3},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle"},ypad:{valType:"number",min:0,dflt:10},outlinecolor:n.linecolor,outlinewidth:n.linewidth,bordercolor:n.linecolor,borderwidth:{valType:"number",min:0,dflt:0},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},tickmode:n.tickmode,nticks:n.nticks,tick0:n.tick0,dtick:n.dtick,tickvals:n.tickvals,ticktext:n.ticktext,ticks:i({},n.ticks,{dflt:""}),ticklen:n.ticklen,tickwidth:n.tickwidth,tickcolor:n.tickcolor,showticklabels:n.showticklabels,tickfont:a({}),tickangle:n.tickangle,tickformat:n.tickformat,tickformatstops:n.tickformatstops,tickprefix:n.tickprefix,showtickprefix:n.showtickprefix,ticksuffix:n.ticksuffix,showticksuffix:n.showticksuffix,separatethousands:n.separatethousands,exponentformat:n.exponentformat,showexponent:n.showexponent,title:{valType:"string"},titlefont:a({}),titleside:{valType:"enumerated",values:["right","top","bottom"],dflt:"top"}},"colorbars","from-root")},{"../../lib/extend":157,"../../plot_api/edit_types":190,"../../plots/cartesian/layout_attributes":219,"../../plots/font_attributes":233}],47:[function(t,e,r){"use strict";var n=t("../colorscale"),a=t("./draw");e.exports=function(t,e,r){if("function"==typeof r)return r(t,e);var i=e[0].trace,o="cb"+i.uid,l=r.container,s=l?i[l]:i;if(t._fullLayout._infolayer.selectAll("."+o).remove(),s&&s.showscale){var c=s[r.min],u=s[r.max],f=e[0].t.cb=a(t,o),d=n.makeColorScaleFunc(n.extractScale(s.colorscale,c,u),{noNumericCheck:!0});f.fillcolor(d).filllevels({start:c,end:u,size:(u-c)/254}).options(s.colorbar)()}}},{"../colorscale":60,"./draw":50}],48:[function(t,e,r){"use strict";e.exports={cn:{colorbar:"colorbar",cbbg:"cbbg",cbfill:"cbfill",cbfills:"cbfills",cbline:"cbline",cblines:"cblines",cbaxis:"cbaxis",cbtitleunshift:"cbtitleunshift",cbtitle:"cbtitle",cboutline:"cboutline",crisp:"crisp",jsPlaceholder:"js-placeholder"}}},{}],49:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plot_api/plot_template"),i=t("../../plots/cartesian/tick_value_defaults"),o=t("../../plots/cartesian/tick_mark_defaults"),l=t("../../plots/cartesian/tick_label_defaults"),s=t("./attributes");e.exports=function(t,e,r){var c=a.newContainer(e,"colorbar"),u=t.colorbar||{};function f(t,e){return n.coerce(u,c,s,t,e)}var d=f("thicknessmode");f("thickness","fraction"===d?30/(r.width-r.margin.l-r.margin.r):30);var p=f("lenmode");f("len","fraction"===p?1:r.height-r.margin.t-r.margin.b),f("x"),f("xanchor"),f("xpad"),f("y"),f("yanchor"),f("ypad"),n.noneOrAll(u,c,["x","y"]),f("outlinecolor"),f("outlinewidth"),f("bordercolor"),f("borderwidth"),f("bgcolor"),i(u,c,f,"linear");var h={outerTicks:!1,font:r.font};l(u,c,f,"linear",h),o(u,c,f,"linear",h),f("title",r._dfltTitle.colorbar),n.coerceFont(f,"titlefont",r.font),f("titleside")}},{"../../lib":163,"../../plot_api/plot_template":197,"../../plots/cartesian/tick_label_defaults":226,"../../plots/cartesian/tick_mark_defaults":227,"../../plots/cartesian/tick_value_defaults":228,"./attributes":46}],50:[function(t,e,r){"use strict";var n=t("d3"),a=t("tinycolor2"),i=t("../../plots/plots"),o=t("../../registry"),l=t("../../plots/cartesian/axes"),s=t("../dragelement"),c=t("../../lib"),u=t("../../lib/extend").extendFlat,f=t("../../lib/setcursor"),d=t("../drawing"),p=t("../color"),h=t("../titles"),g=t("../../lib/svg_text_utils"),y=t("../../constants/alignment"),v=y.LINE_SPACING,m=y.FROM_TL,x=y.FROM_BR,b=t("../../plots/cartesian/axis_defaults"),_=t("../../plots/cartesian/position_defaults"),w=t("../../plots/cartesian/layout_attributes"),k=t("./attributes"),M=t("./constants").cn;e.exports=function(t,e){var r={};function y(){var k=t._fullLayout,A=k._size;if("function"==typeof r.fillcolor||"function"==typeof r.line.color){var L,C,S=n.extent(("function"==typeof r.fillcolor?r.fillcolor:r.line.color).domain()),O=[],P=[],D="function"==typeof r.line.color?r.line.color:function(){return r.line.color},z="function"==typeof r.fillcolor?r.fillcolor:function(){return r.fillcolor},E=r.levels.end+r.levels.size/100,I=r.levels.size,N=1.001*S[0]-.001*S[1],R=1.001*S[1]-.001*S[0];for(C=0;C<1e5&&(L=r.levels.start+C*I,!(I>0?L>=E:L<=E));C++)L>N&&L<R&&O.push(L);if("function"==typeof r.fillcolor)if(r.filllevels)for(E=r.filllevels.end+r.filllevels.size/100,I=r.filllevels.size,C=0;C<1e5&&(L=r.filllevels.start+C*I,!(I>0?L>=E:L<=E));C++)L>S[0]&&L<S[1]&&P.push(L);else(P=O.map(function(t){return t-r.levels.size/2})).push(P[P.length-1]+r.levels.size);else r.fillcolor&&"string"==typeof r.fillcolor&&(P=[0]);r.levels.size<0&&(O.reverse(),P.reverse());var F,j=A.h,B=A.w,H=Math.round(r.thickness*("fraction"===r.thicknessmode?B:1)),q=H/A.w,V=Math.round(r.len*("fraction"===r.lenmode?j:1)),U=V/A.h,G=r.xpad/A.w,Y=(r.borderwidth+r.outlinewidth)/2,X=r.ypad/A.h,Z=Math.round(r.x*A.w+r.xpad),W=r.x-q*({middle:.5,right:1}[r.xanchor]||0),Q=r.y+U*(({top:-.5,bottom:.5}[r.yanchor]||0)-.5),J=Math.round(A.h*(1-Q)),$=J-V,K={type:"linear",range:S,tickmode:r.tickmode,nticks:r.nticks,tick0:r.tick0,dtick:r.dtick,tickvals:r.tickvals,ticktext:r.ticktext,ticks:r.ticks,ticklen:r.ticklen,tickwidth:r.tickwidth,tickcolor:r.tickcolor,showticklabels:r.showticklabels,tickfont:r.tickfont,tickangle:r.tickangle,tickformat:r.tickformat,exponentformat:r.exponentformat,separatethousands:r.separatethousands,showexponent:r.showexponent,showtickprefix:r.showtickprefix,tickprefix:r.tickprefix,showticksuffix:r.showticksuffix,ticksuffix:r.ticksuffix,title:r.title,titlefont:r.titlefont,showline:!0,anchor:"free",position:1},tt={type:"linear",_id:"y"+e},et={letter:"y",font:k.font,noHover:!0,calendar:k.calendar};if(b(K,tt,yt,et,k),_(K,tt,yt,et),tt.position=r.x+G+q,y.axis=tt,-1!==["top","bottom"].indexOf(r.titleside)&&(tt.titleside=r.titleside,tt.titlex=r.x+G,tt.titley=Q+("top"===r.titleside?U-X:X)),r.line.color&&"auto"===r.tickmode){tt.tickmode="linear",tt.tick0=r.levels.start;var rt=r.levels.size,nt=c.constrain((J-$)/50,4,15)+1,at=(S[1]-S[0])/((r.nticks||nt)*rt);if(at>1){var it=Math.pow(10,Math.floor(Math.log(at)/Math.LN10));rt*=it*c.roundUp(at/it,[2,5,10]),(Math.abs(r.levels.start)/r.levels.size+1e-6)%1<2e-6&&(tt.tick0=0)}tt.dtick=rt}tt.domain=[Q+X,Q+U-X],tt.setScale();var ot=c.ensureSingle(k._infolayer,"g",e,function(t){t.classed(M.colorbar,!0).each(function(){var t=n.select(this);t.append("rect").classed(M.cbbg,!0),t.append("g").classed(M.cbfills,!0),t.append("g").classed(M.cblines,!0),t.append("g").classed(M.cbaxis,!0).classed(M.crisp,!0),t.append("g").classed(M.cbtitleunshift,!0).append("g").classed(M.cbtitle,!0),t.append("rect").classed(M.cboutline,!0),t.select(".cbtitle").datum(0)})});ot.attr("transform","translate("+Math.round(A.l)+","+Math.round(A.t)+")");var lt=ot.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(A.l)+",-"+Math.round(A.t)+")");tt._axislayer=ot.select(".cbaxis");var st=0;if(-1!==["top","bottom"].indexOf(r.titleside)){var ct,ut=A.l+(r.x+G)*A.w,ft=tt.titlefont.size;ct="top"===r.titleside?(1-(Q+U-X))*A.h+A.t+3+.75*ft:(1-(Q+X))*A.h+A.t-3-.25*ft,vt(tt._id+"title",{attributes:{x:ut,y:ct,"text-anchor":"start"}})}var dt,pt,ht,gt=c.syncOrAsync([i.previousPromises,function(){if(-1!==["top","bottom"].indexOf(r.titleside)){var e=ot.select(".cbtitle"),i=e.select("text"),o=[-r.outlinewidth/2,r.outlinewidth/2],s=e.select(".h"+tt._id+"title-math-group").node(),u=15.6;if(i.node()&&(u=parseInt(i.node().style.fontSize,10)*v),s?(st=d.bBox(s).height)>u&&(o[1]-=(st-u)/2):i.node()&&!i.classed(M.jsPlaceholder)&&(st=d.bBox(i.node()).height),st){if(st+=5,"top"===r.titleside)tt.domain[1]-=st/A.h,o[1]*=-1;else{tt.domain[0]+=st/A.h;var f=g.lineCount(i);o[1]+=(1-f)*u}e.attr("transform","translate("+o+")"),tt.setScale()}}ot.selectAll(".cbfills,.cblines").attr("transform","translate(0,"+Math.round(A.h*(1-tt.domain[1]))+")"),tt._axislayer.attr("transform","translate(0,"+Math.round(-A.t)+")");var p=ot.select(".cbfills").selectAll("rect.cbfill").data(P);p.enter().append("rect").classed(M.cbfill,!0).style("stroke","none"),p.exit().remove(),p.each(function(t,e){var r=[0===e?S[0]:(P[e]+P[e-1])/2,e===P.length-1?S[1]:(P[e]+P[e+1])/2].map(tt.c2p).map(Math.round);e!==P.length-1&&(r[1]+=r[1]>r[0]?1:-1);var i=z(t).replace("e-",""),o=a(i).toHexString();n.select(this).attr({x:Z,width:Math.max(H,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2),fill:o})});var h=ot.select(".cblines").selectAll("path.cbline").data(r.line.color&&r.line.width?O:[]);return h.enter().append("path").classed(M.cbline,!0),h.exit().remove(),h.each(function(t){n.select(this).attr("d","M"+Z+","+(Math.round(tt.c2p(t))+r.line.width/2%1)+"h"+H).call(d.lineGroupStyle,r.line.width,D(t),r.line.dash)}),tt._axislayer.selectAll("g."+tt._id+"tick,path").remove(),tt._pos=Z+H+(r.outlinewidth||0)/2-("outside"===r.ticks?1:0),tt.side="right",c.syncOrAsync([function(){return l.doTicksSingle(t,tt,!0)},function(){if(-1===["top","bottom"].indexOf(r.titleside)){var e=tt.titlefont.size,a=tt._offset+tt._length/2,i=A.l+(tt.position||0)*A.w+("right"===tt.side?10+e*(tt.showticklabels?1:.5):-10-e*(tt.showticklabels?.5:0));vt("h"+tt._id+"title",{avoid:{selection:n.select(t).selectAll("g."+tt._id+"tick"),side:r.titleside,offsetLeft:A.l,offsetTop:0,maxShift:k.width},attributes:{x:i,y:a,"text-anchor":"middle"},transform:{rotate:"-90",offset:0}})}}])},i.previousPromises,function(){var n=H+r.outlinewidth/2+d.bBox(tt._axislayer.node()).width;if((F=lt.select("text")).node()&&!F.classed(M.jsPlaceholder)){var a,o=lt.select(".h"+tt._id+"title-math-group").node();a=o&&-1!==["top","bottom"].indexOf(r.titleside)?d.bBox(o).width:d.bBox(lt.node()).right-Z-A.l,n=Math.max(n,a)}var l=2*r.xpad+n+r.borderwidth+r.outlinewidth/2,s=J-$;ot.select(".cbbg").attr({x:Z-r.xpad-(r.borderwidth+r.outlinewidth)/2,y:$-Y,width:Math.max(l,2),height:Math.max(s+2*Y,2)}).call(p.fill,r.bgcolor).call(p.stroke,r.bordercolor).style({"stroke-width":r.borderwidth}),ot.selectAll(".cboutline").attr({x:Z,y:$+r.ypad+("top"===r.titleside?st:0),width:Math.max(H,2),height:Math.max(s-2*r.ypad-st,2)}).call(p.stroke,r.outlinecolor).style({fill:"None","stroke-width":r.outlinewidth});var c=({center:.5,right:1}[r.xanchor]||0)*l;ot.attr("transform","translate("+(A.l-c)+","+A.t+")");var u={},f=m[r.yanchor],h=x[r.yanchor];"pixels"===r.lenmode?(u.y=r.y,u.t=s*f,u.b=s*h):(u.t=u.b=0,u.yt=r.y+r.len*f,u.yb=r.y-r.len*h);var g=m[r.xanchor],y=x[r.xanchor];if("pixels"===r.thicknessmode)u.x=r.x,u.l=l*g,u.r=l*y;else{var v=l-H;u.l=v*g,u.r=v*y,u.xl=r.x-r.thickness*g,u.xr=r.x+r.thickness*y}i.autoMargin(t,e,u)}],t);if(gt&&gt.then&&(t._promises||[]).push(gt),t._context.edits.colorbarPosition)s.init({element:ot.node(),gd:t,prepFn:function(){dt=ot.attr("transform"),f(ot)},moveFn:function(t,e){ot.attr("transform",dt+" translate("+t+","+e+")"),pt=s.align(W+t/A.w,q,0,1,r.xanchor),ht=s.align(Q-e/A.h,U,0,1,r.yanchor);var n=s.getCursor(pt,ht,r.xanchor,r.yanchor);f(ot,n)},doneFn:function(){f(ot),void 0!==pt&&void 0!==ht&&o.call("restyle",t,{"colorbar.x":pt,"colorbar.y":ht},T().index)}});return gt}function yt(t,e){return c.coerce(K,tt,w,t,e)}function vt(e,r){var n=T(),a="colorbar.title",i=n._module.colorbar.container;i&&(a=i+"."+a);var o={propContainer:tt,propName:a,traceIndex:n.index,placeholder:k._dfltTitle.colorbar,containerGroup:ot.select(".cbtitle")},l="h"===e.charAt(0)?e.substr(1):"h"+e;ot.selectAll("."+l+",."+l+"-math-group").remove(),h.draw(t,e,u(o,r||{}))}k._infolayer.selectAll("g."+e).remove()}function T(){var r,n,a=e.substr(2);for(r=0;r<t._fullData.length;r++)if((n=t._fullData[r]).uid===a)return n}return Object.keys(k).forEach(function(t){r[t]=null}),r.fillcolor=null,r.line={color:null,width:null,dash:null},r.levels={start:null,end:null,size:null},r.filllevels=null,Object.keys(r).forEach(function(t){y[t]=function(e){return arguments.length?(r[t]=c.isPlainObject(r[t])?c.extendFlat(r[t],e):e,y):r[t]}}),y.options=function(t){return Object.keys(t).forEach(function(e){"function"==typeof y[e]&&y[e](t[e])}),y},y._opts=r,y}},{"../../constants/alignment":143,"../../lib":163,"../../lib/extend":157,"../../lib/setcursor":182,"../../lib/svg_text_utils":184,"../../plots/cartesian/axes":207,"../../plots/cartesian/axis_defaults":209,"../../plots/cartesian/layout_attributes":219,"../../plots/cartesian/position_defaults":222,"../../plots/plots":239,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"../titles":136,"./attributes":46,"./constants":48,d3:10,tinycolor2:28}],51:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t){return n.isPlainObject(t.colorbar)}},{"../../lib":163}],52:[function(t,e,r){"use strict";var n=t("./scales.js");Object.keys(n);function a(t){return"`"+t+"`"}e.exports=function(t,e){t=t||"";var r,i=(e=e||{}).cLetter||"c",o=("onlyIfNumerical"in e?e.onlyIfNumerical:Boolean(t),"noScale"in e?e.noScale:"marker.line"===t),l="showScaleDflt"in e?e.showScaleDflt:"z"===i,s="string"==typeof e.colorscaleDflt?n[e.colorscaleDflt]:null,c=e.editTypeOverride||"",u=t?t+".":"";"colorAttr"in e?(r=e.colorAttr,e.colorAttr):a(u+(r={z:"z",c:"color"}[i]));var f=i+"auto",d=i+"min",p=i+"max",h=(a(u+d),a(u+p),{});h[d]=h[p]=void 0;var g={};g[f]=!1;var y={};return"color"===r&&(y.color={valType:"color",arrayOk:!0,editType:c||"style"}),y[f]={valType:"boolean",dflt:!0,editType:"calc",impliedEdits:h},y[d]={valType:"number",dflt:null,editType:c||"plot",impliedEdits:g},y[p]={valType:"number",dflt:null,editType:c||"plot",impliedEdits:g},y.colorscale={valType:"colorscale",editType:"calc",dflt:s,impliedEdits:{autocolorscale:!1}},y.autocolorscale={valType:"boolean",dflt:!1!==e.autoColorDflt,editType:"calc",impliedEdits:{colorscale:void 0}},y.reversescale={valType:"boolean",dflt:!1,editType:"calc"},o||(y.showscale={valType:"boolean",dflt:l,editType:"calc"}),y}},{"./scales.js":64}],53:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./scales"),i=t("./flip_scale");e.exports=function(t,e,r,o){var l=t,s=t._input,c=t._fullInput,u=t.updateStyle;function f(e,n,a){void 0===a&&(a=n),u?u(t._input,r?r+"."+e:e,n):s[e]=n,l[e]=a,c&&t!==t._fullInput&&(u?u(t._fullInput,r?r+"."+e:e,a):c[e]=a)}r&&(l=n.nestedProperty(l,r).get(),s=n.nestedProperty(s,r).get(),c=n.nestedProperty(c,r).get()||{});var d=o+"auto",p=o+"min",h=o+"max",g=l[d],y=l[p],v=l[h],m=l.colorscale;!1===g&&void 0!==y||(y=n.aggNums(Math.min,null,e)),!1===g&&void 0!==v||(v=n.aggNums(Math.max,null,e)),y===v&&(y-=.5,v+=.5),f(p,y),f(h,v),f(d,!1!==g||void 0===y&&void 0===v),l.autocolorscale&&(f("colorscale",m=y*v<0?a.RdBu:y>=0?a.Reds:a.Blues,l.reversescale?i(m):m),s.autocolorscale||f("autocolorscale",!1))}},{"../../lib":163,"./flip_scale":57,"./scales":64}],54:[function(t,e,r){"use strict";var n=t("./scales");e.exports=n.RdBu},{"./scales":64}],55:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),l=t("./is_valid_scale"),s=t("./flip_scale");e.exports=function(t,e,r,c,u){var f,d=u.prefix,p=u.cLetter,h=d.slice(0,d.length-1),g=d?a.nestedProperty(t,h).get()||{}:t,y=d?a.nestedProperty(e,h).get()||{}:e,v=g[p+"min"],m=g[p+"max"],x=g.colorscale;c(d+p+"auto",!(n(v)&&n(m)&&v<m)),c(d+p+"min"),c(d+p+"max"),void 0!==x&&(f=!l(x)),c(d+"autocolorscale",f);var b,_=c(d+"colorscale");(c(d+"reversescale")&&(y.colorscale=s(_)),"marker.line."!==d)&&(d&&(b=i(g)),c(d+"showscale",b)&&o(g,y,r))}},{"../../lib":163,"../colorbar/defaults":49,"../colorbar/has_colorbar":51,"./flip_scale":57,"./is_valid_scale":61,"fast-isnumeric":13}],56:[function(t,e,r){"use strict";e.exports=function(t,e,r){for(var n=t.length,a=new Array(n),i=new Array(n),o=0;o<n;o++){var l=t[o];a[o]=e+l[0]*(r-e),i[o]=l[1]}return{domain:a,range:i}}},{}],57:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=t.length,n=new Array(r),a=r-1,i=0;a>=0;a--,i++)e=t[a],n[i]=[1-e[0],e[1]];return n}},{}],58:[function(t,e,r){"use strict";var n=t("./scales"),a=t("./default_scale"),i=t("./is_valid_scale_array");e.exports=function(t,e){if(e||(e=a),!t)return e;function r(){try{t=n[t]||JSON.parse(t)}catch(r){t=e}}return"string"==typeof t&&(r(),"string"==typeof t&&r()),i(t)?t:e}},{"./default_scale":54,"./is_valid_scale_array":62,"./scales":64}],59:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("./is_valid_scale");e.exports=function(t,e){var r=e?a.nestedProperty(t,e).get()||{}:t,o=r.color,l=!1;if(a.isArrayOrTypedArray(o))for(var s=0;s<o.length;s++)if(n(o[s])){l=!0;break}return a.isPlainObject(r)&&(l||!0===r.showscale||n(r.cmin)&&n(r.cmax)||i(r.colorscale)||a.isPlainObject(r.colorbar))}},{"../../lib":163,"./is_valid_scale":61,"fast-isnumeric":13}],60:[function(t,e,r){"use strict";r.scales=t("./scales"),r.defaultScale=t("./default_scale"),r.attributes=t("./attributes"),r.handleDefaults=t("./defaults"),r.calc=t("./calc"),r.hasColorscale=t("./has_colorscale"),r.isValidScale=t("./is_valid_scale"),r.getScale=t("./get_scale"),r.flipScale=t("./flip_scale"),r.extractScale=t("./extract_scale"),r.makeColorScaleFunc=t("./make_color_scale_func")},{"./attributes":52,"./calc":53,"./default_scale":54,"./defaults":55,"./extract_scale":56,"./flip_scale":57,"./get_scale":58,"./has_colorscale":59,"./is_valid_scale":61,"./make_color_scale_func":63,"./scales":64}],61:[function(t,e,r){"use strict";var n=t("./scales"),a=t("./is_valid_scale_array");e.exports=function(t){return void 0!==n[t]||a(t)}},{"./is_valid_scale_array":62,"./scales":64}],62:[function(t,e,r){"use strict";var n=t("tinycolor2");e.exports=function(t){var e=0;if(!Array.isArray(t)||t.length<2)return!1;if(!t[0]||!t[t.length-1])return!1;if(0!=+t[0][0]||1!=+t[t.length-1][0])return!1;for(var r=0;r<t.length;r++){var a=t[r];if(2!==a.length||+a[0]<e||!n(a[1]).isValid())return!1;e=+a[0]}return!0}},{tinycolor2:28}],63:[function(t,e,r){"use strict";var n=t("d3"),a=t("tinycolor2"),i=t("fast-isnumeric"),o=t("../color");function l(t){var e={r:t[0],g:t[1],b:t[2],a:t[3]};return a(e).toRgbString()}e.exports=function(t,e){e=e||{};for(var r=t.domain,s=t.range,c=s.length,u=new Array(c),f=0;f<c;f++){var d=a(s[f]).toRgb();u[f]=[d.r,d.g,d.b,d.a]}var p,h=n.scale.linear().domain(r).range(u).clamp(!0),g=e.noNumericCheck,y=e.returnArray;return(p=g&&y?h:g?function(t){return l(h(t))}:y?function(t){return i(t)?h(t):a(t).isValid()?t:o.defaultLine}:function(t){return i(t)?l(h(t)):a(t).isValid()?t:o.defaultLine}).domain=h.domain,p.range=function(){return s},p}},{"../color":45,d3:10,"fast-isnumeric":13,tinycolor2:28}],64:[function(t,e,r){"use strict";e.exports={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]],Cividis:[[0,"rgb(0,32,76)"],[.058824,"rgb(0,42,102)"],[.117647,"rgb(0,52,110)"],[.176471,"rgb(39,63,108)"],[.235294,"rgb(60,74,107)"],[.294118,"rgb(76,85,107)"],[.352941,"rgb(91,95,109)"],[.411765,"rgb(104,106,112)"],[.470588,"rgb(117,117,117)"],[.529412,"rgb(131,129,120)"],[.588235,"rgb(146,140,120)"],[.647059,"rgb(161,152,118)"],[.705882,"rgb(176,165,114)"],[.764706,"rgb(192,177,109)"],[.823529,"rgb(209,191,102)"],[.882353,"rgb(225,204,92)"],[.941176,"rgb(243,219,79)"],[1,"rgb(255,233,69)"]]}},{}],65:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,a){var i=(t-r)/(n-r),o=i+e/(n-r),l=(i+o)/2;return"left"===a||"bottom"===a?i:"center"===a||"middle"===a?l:"right"===a||"top"===a?o:i<2/3-l?i:o>4/3-l?o:l}},{}],66:[function(t,e,r){"use strict";var n=t("../../lib"),a=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];e.exports=function(t,e,r,i){return t="left"===r?0:"center"===r?1:"right"===r?2:n.constrain(Math.floor(3*t),0,2),e="bottom"===i?0:"middle"===i?1:"top"===i?2:n.constrain(Math.floor(3*e),0,2),a[e][t]}},{"../../lib":163}],67:[function(t,e,r){"use strict";var n=t("mouse-event-offset"),a=t("has-hover"),i=t("has-passive-events"),o=t("../../registry"),l=t("../../lib"),s=t("../../plots/cartesian/constants"),c=t("../../constants/interactions"),u=e.exports={};u.align=t("./align"),u.getCursor=t("./cursor");var f=t("./unhover");function d(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}function p(t){return n(t.changedTouches?t.changedTouches[0]:t,document.body)}u.unhover=f.wrapped,u.unhoverRaw=f.raw,u.init=function(t){var e,r,n,f,h,g,y,v,m=t.gd,x=1,b=c.DBLCLICKDELAY,_=t.element;m._mouseDownTime||(m._mouseDownTime=0),_.style.pointerEvents="all",_.onmousedown=k,i?(_._ontouchstart&&_.removeEventListener("touchstart",_._ontouchstart),_._ontouchstart=k,_.addEventListener("touchstart",k,{passive:!1})):_.ontouchstart=k;var w=t.clampFn||function(t,e,r){return Math.abs(t)<r&&(t=0),Math.abs(e)<r&&(e=0),[t,e]};function k(i){i.preventDefault(),m._dragged=!1,m._dragging=!0;var o=p(i);e=o[0],r=o[1],y=i.target,g=i,v=2===i.buttons||i.ctrlKey,(n=(new Date).getTime())-m._mouseDownTime<b?x+=1:(x=1,m._mouseDownTime=n),t.prepFn&&t.prepFn(i,e,r),a&&!v?(h=d()).style.cursor=window.getComputedStyle(_).cursor:a||(h=document,f=window.getComputedStyle(document.documentElement).cursor,document.documentElement.style.cursor=window.getComputedStyle(_).cursor),document.addEventListener("mousemove",M),document.addEventListener("mouseup",T),document.addEventListener("touchmove",M),document.addEventListener("touchend",T)}function M(n){n.preventDefault();var a=p(n),i=t.minDrag||s.MINDRAG,o=w(a[0]-e,a[1]-r,i),l=o[0],c=o[1];(l||c)&&(m._dragged=!0,u.unhover(m)),m._dragged&&t.moveFn&&!v&&t.moveFn(l,c)}function T(e){if(document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",T),document.removeEventListener("touchmove",M),document.removeEventListener("touchend",T),e.preventDefault(),a?l.removeElement(h):f&&(h.documentElement.style.cursor=f,f=null),m._dragging){if(m._dragging=!1,(new Date).getTime()-m._mouseDownTime>b&&(x=Math.max(x-1,1)),m._dragged)t.doneFn&&t.doneFn();else if(t.clickFn&&t.clickFn(x,g),!v){var r;try{r=new MouseEvent("click",e)}catch(t){var n=p(e);(r=document.createEvent("MouseEvents")).initMouseEvent("click",e.bubbles,e.cancelable,e.view,e.detail,e.screenX,e.screenY,n[0],n[1],e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,e.button,e.relatedTarget)}y.dispatchEvent(r)}!function(t){t._dragging=!1,t._replotPending&&o.call("plot",t)}(m),m._dragged=!1}else m._dragged=!1}},u.coverSlip=d},{"../../constants/interactions":144,"../../lib":163,"../../plots/cartesian/constants":212,"../../registry":247,"./align":65,"./cursor":66,"./unhover":68,"has-hover":15,"has-passive-events":16,"mouse-event-offset":18}],68:[function(t,e,r){"use strict";var n=t("../../lib/events"),a=t("../../lib/throttle"),i=t("../../lib/get_graph_div"),o=t("../fx/constants"),l=e.exports={};l.wrapped=function(t,e,r){(t=i(t))._fullLayout&&a.clear(t._fullLayout._uid+o.HOVERID),l.raw(t,e,r)},l.raw=function(t,e){var r=t._fullLayout,a=t._hoverdata;e||(e={}),e.target&&!1===n.triggerHandler(t,"plotly_beforehover",e)||(r._hoverlayer.selectAll("g").remove(),r._hoverlayer.selectAll("line").remove(),r._hoverlayer.selectAll("circle").remove(),t._hoverdata=void 0,e.target&&a&&t.emit("plotly_unhover",{event:e,points:a}))}},{"../../lib/events":156,"../../lib/get_graph_div":161,"../../lib/throttle":185,"../fx/constants":82}],69:[function(t,e,r){"use strict";r.dash={valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},{}],70:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("tinycolor2"),o=t("../../registry"),l=t("../color"),s=t("../colorscale"),c=t("../../lib"),u=t("../../lib/svg_text_utils"),f=t("../../constants/xmlns_namespaces"),d=t("../../constants/alignment").LINE_SPACING,p=t("../../constants/interactions").DESELECTDIM,h=t("../../traces/scatter/subtypes"),g=t("../../traces/scatter/make_bubble_size_func"),y=e.exports={};y.font=function(t,e,r,n){c.isPlainObject(e)&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(l.fill,n)},y.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},y.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},y.setRect=function(t,e,r,n,a){t.call(y.setPosition,e,r).call(y.setSize,n,a)},y.translatePoint=function(t,e,r,n){var i=r.c2p(t.x),o=n.c2p(t.y);return!!(a(i)&&a(o)&&e.node())&&("text"===e.node().nodeName?e.attr("x",i).attr("y",o):e.attr("transform","translate("+i+","+o+")"),!0)},y.translatePoints=function(t,e,r){t.each(function(t){var a=n.select(this);y.translatePoint(t,a,e,r)})},y.hideOutsideRangePoint=function(t,e,r,n,a,i){e.attr("display",r.isPtWithinRange(t,a)&&n.isPtWithinRange(t,i)?null:"none")},y.hideOutsideRangePoints=function(t,e){if(e._hasClipOnAxisFalse){var r=e.xaxis,a=e.yaxis;t.each(function(e){var i=e[0].trace,o=i.xcalendar,l=i.ycalendar,s="bar"===i.type?".bartext":".point,.textpoint";t.selectAll(s).each(function(t){y.hideOutsideRangePoint(t,n.select(this),r,a,o,l)})})}},y.crispRound=function(t,e,r){return e&&a(e)?t._context.staticPlot?e:e<1?1:Math.round(e):r||0},y.singleLineStyle=function(t,e,r,n,a){e.style("fill","none");var i=(((t||[])[0]||{}).trace||{}).line||{},o=r||i.width||0,s=a||i.dash||"";l.stroke(e,n||i.color),y.dashLine(e,s,o)},y.lineGroupStyle=function(t,e,r,a){t.style("fill","none").each(function(t){var i=(((t||[])[0]||{}).trace||{}).line||{},o=e||i.width||0,s=a||i.dash||"";n.select(this).call(l.stroke,r||i.color).call(y.dashLine,s,o)})},y.dashLine=function(t,e,r){r=+r||0,e=y.dashStyle(e,r),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},y.dashStyle=function(t,e){e=+e||1;var r=Math.max(e,3);return"solid"===t?t="":"dot"===t?t=r+"px,"+r+"px":"dash"===t?t=3*r+"px,"+3*r+"px":"longdash"===t?t=5*r+"px,"+5*r+"px":"dashdot"===t?t=3*r+"px,"+r+"px,"+r+"px,"+r+"px":"longdashdot"===t&&(t=5*r+"px,"+2*r+"px,"+r+"px,"+2*r+"px"),t},y.singleFillStyle=function(t){var e=(((n.select(t.node()).data()[0]||[])[0]||{}).trace||{}).fillcolor;e&&t.call(l.fill,e)},y.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=n.select(this);try{r.call(l.fill,e[0].trace.fillcolor)}catch(e){c.error(e,t),r.remove()}})};var v=t("./symbol_defs");y.symbolNames=[],y.symbolFuncs=[],y.symbolNeedLines={},y.symbolNoDot={},y.symbolNoFill={},y.symbolList=[],Object.keys(v).forEach(function(t){var e=v[t];y.symbolList=y.symbolList.concat([e.n,t,e.n+100,t+"-open"]),y.symbolNames[e.n]=t,y.symbolFuncs[e.n]=e.f,e.needLine&&(y.symbolNeedLines[e.n]=!0),e.noDot?y.symbolNoDot[e.n]=!0:y.symbolList=y.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"]),e.noFill&&(y.symbolNoFill[e.n]=!0)});var m=y.symbolNames.length,x="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";function b(t,e){var r=t%100;return y.symbolFuncs[r](e)+(t>=200?x:"")}y.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),(t=y.symbolNames.indexOf(t))>=0&&(t+=e)}return t%100>=m||t>=400?0:Math.floor(Math.max(t,0))};var _={x1:1,x2:0,y1:0,y2:0},w={x1:0,x2:0,y1:1,y2:0};y.gradient=function(t,e,r,a,o,s){var u=e._fullLayout._defs.select(".gradients").selectAll("#"+r).data([a+o+s],c.identity);u.exit().remove(),u.enter().append("radial"===a?"radialGradient":"linearGradient").each(function(){var t=n.select(this);"horizontal"===a?t.attr(_):"vertical"===a&&t.attr(w),t.attr("id",r);var e=i(o),c=i(s);t.append("stop").attr({offset:"0%","stop-color":l.tinyRGB(c),"stop-opacity":c.getAlpha()}),t.append("stop").attr({offset:"100%","stop-color":l.tinyRGB(e),"stop-opacity":e.getAlpha()})}),t.style({fill:"url(#"+r+")","fill-opacity":null})},y.initGradients=function(t){c.ensureSingle(t._fullLayout._defs,"g","gradients").selectAll("linearGradient,radialGradient").remove()},y.pointStyle=function(t,e,r){if(t.size()){var a=y.makePointStyleFns(e);t.each(function(t){y.singlePointStyle(t,n.select(this),e,a,r)})}},y.singlePointStyle=function(t,e,r,n,a){var i=r.marker,o=i.line;if(e.style("opacity",n.selectedOpacityFn?n.selectedOpacityFn(t):void 0===t.mo?i.opacity:t.mo),n.ms2mrc){var s;s="various"===t.ms||"various"===i.size?3:n.ms2mrc(t.ms),t.mrc=s,n.selectedSizeFn&&(s=t.mrc=n.selectedSizeFn(t));var u=y.symbolNumber(t.mx||i.symbol)||0;t.om=u%200>=100,e.attr("d",b(u,s))}var f,d,p,h=!1;if(t.so)p=o.outlierwidth,d=o.outliercolor,f=i.outliercolor;else{var g=(o||{}).width;p=(t.mlw+1||g+1||(t.trace?(t.trace.marker.line||{}).width:0)+1)-1||0,d="mlc"in t?t.mlcc=n.lineScale(t.mlc):c.isArrayOrTypedArray(o.color)?l.defaultLine:o.color,c.isArrayOrTypedArray(i.color)&&(f=l.defaultLine,h=!0),f="mc"in t?t.mcc=n.markerScale(t.mc):i.color||"rgba(0,0,0,0)",n.selectedColorFn&&(f=n.selectedColorFn(t))}if(t.om)e.call(l.stroke,f).style({"stroke-width":(p||1)+"px",fill:"none"});else{e.style("stroke-width",p+"px");var v=i.gradient,m=t.mgt;if(m?h=!0:m=v&&v.type,m&&"none"!==m){var x=t.mgc;x?h=!0:x=v.color;var _="g"+a._fullLayout._uid+"-"+r.uid;h&&(_+="-"+t.i),e.call(y.gradient,a,_,m,f,x)}else e.call(l.fill,f);p&&e.call(l.stroke,d)}},y.makePointStyleFns=function(t){var e={},r=t.marker;return e.markerScale=y.tryColorscale(r,""),e.lineScale=y.tryColorscale(r,"line"),o.traceIs(t,"symbols")&&(e.ms2mrc=h.isBubble(t)?g(t):function(){return(r.size||6)/2}),t.selectedpoints&&c.extendFlat(e,y.makeSelectedPointStyleFns(t)),e},y.makeSelectedPointStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},a=t.marker||{},i=r.marker||{},l=n.marker||{},s=a.opacity,u=i.opacity,f=l.opacity,d=void 0!==u,h=void 0!==f;(c.isArrayOrTypedArray(s)||d||h)&&(e.selectedOpacityFn=function(t){var e=void 0===t.mo?a.opacity:t.mo;return t.selected?d?u:e:h?f:p*e});var g=a.color,y=i.color,v=l.color;(y||v)&&(e.selectedColorFn=function(t){var e=t.mcc||g;return t.selected?y||e:v||e});var m=a.size,x=i.size,b=l.size,_=void 0!==x,w=void 0!==b;return o.traceIs(t,"symbols")&&(_||w)&&(e.selectedSizeFn=function(t){var e=t.mrc||m/2;return t.selected?_?x/2:e:w?b/2:e}),e},y.makeSelectedTextStyleFns=function(t){var e={},r=t.selected||{},n=t.unselected||{},a=t.textfont||{},i=r.textfont||{},o=n.textfont||{},s=a.color,c=i.color,u=o.color;return e.selectedTextColorFn=function(t){var e=t.tc||s;return t.selected?c||e:u||(c?e:l.addOpacity(e,p))},e},y.selectedPointStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=y.makeSelectedPointStyleFns(e),a=e.marker||{},i=[];r.selectedOpacityFn&&i.push(function(t,e){t.style("opacity",r.selectedOpacityFn(e))}),r.selectedColorFn&&i.push(function(t,e){l.fill(t,r.selectedColorFn(e))}),r.selectedSizeFn&&i.push(function(t,e){var n=e.mx||a.symbol||0,i=r.selectedSizeFn(e);t.attr("d",b(y.symbolNumber(n),i)),e.mrc2=i}),i.length&&t.each(function(t){for(var e=n.select(this),r=0;r<i.length;r++)i[r](e,t)})}},y.tryColorscale=function(t,e){var r=e?c.nestedProperty(t,e).get():t;if(r){var n=r.colorscale,a=r.color;if(n&&c.isArrayOrTypedArray(a))return s.makeColorScaleFunc(s.extractScale(n,r.cmin,r.cmax))}return c.identity};var k={start:1,end:-1,middle:0,bottom:1,top:-1};function M(t,e,r,a){var i=n.select(t.node().parentNode),o=-1!==e.indexOf("top")?"top":-1!==e.indexOf("bottom")?"bottom":"middle",l=-1!==e.indexOf("left")?"end":-1!==e.indexOf("right")?"start":"middle",s=a?a/.8+1:0,c=(u.lineCount(t)-1)*d+1,f=k[l]*s,p=.75*r+k[o]*s+(k[o]-1)*c*r/2;t.attr("text-anchor",l),i.attr("transform","translate("+f+","+p+")")}function T(t,e){var r=t.ts||e.textfont.size;return a(r)&&r>0?r:0}y.textPointStyle=function(t,e,r){if(t.size()){var a;if(e.selectedpoints){var i=y.makeSelectedTextStyleFns(e);a=i.selectedTextColorFn}t.each(function(t){var i=n.select(this),o=c.extractOption(t,e,"tx","text");if(o||0===o){var l=t.tp||e.textposition,s=T(t,e),f=a?a(t):t.tc||e.textfont.color;i.call(y.font,t.tf||e.textfont.family,s,f).text(o).call(u.convertToTspans,r).call(M,l,s,t.mrc)}else i.remove()})}},y.selectedTextStyle=function(t,e){if(t.size()&&e.selectedpoints){var r=y.makeSelectedTextStyleFns(e);t.each(function(t){var a=n.select(this),i=r.selectedTextColorFn(t),o=t.tp||e.textposition,s=T(t,e);l.fill(a,i),M(a,o,s,t.mrc2||t.mrc)})}};var A=.5;function L(t,e,r,a){var i=t[0]-e[0],o=t[1]-e[1],l=r[0]-e[0],s=r[1]-e[1],c=Math.pow(i*i+o*o,A/2),u=Math.pow(l*l+s*s,A/2),f=(u*u*i-c*c*l)*a,d=(u*u*o-c*c*s)*a,p=3*u*(c+u),h=3*c*(c+u);return[[n.round(e[0]+(p&&f/p),2),n.round(e[1]+(p&&d/p),2)],[n.round(e[0]-(h&&f/h),2),n.round(e[1]-(h&&d/h),2)]]}y.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,n="M"+t[0],a=[];for(r=1;r<t.length-1;r++)a.push(L(t[r-1],t[r],t[r+1],e));for(n+="Q"+a[0][0]+" "+t[1],r=2;r<t.length-1;r++)n+="C"+a[r-2][1]+" "+a[r-1][0]+" "+t[r];return n+="Q"+a[t.length-3][1]+" "+t[t.length-1]},y.smoothclosed=function(t,e){if(t.length<3)return"M"+t.join("L")+"Z";var r,n="M"+t[0],a=t.length-1,i=[L(t[a],t[0],t[1],e)];for(r=1;r<a;r++)i.push(L(t[r-1],t[r],t[r+1],e));for(i.push(L(t[a-1],t[a],t[0],e)),r=1;r<=a;r++)n+="C"+i[r-1][1]+" "+i[r][0]+" "+t[r];return n+="C"+i[a][1]+" "+i[0][0]+" "+t[0]+"Z"};var C={hv:function(t,e){return"H"+n.round(e[0],2)+"V"+n.round(e[1],2)},vh:function(t,e){return"V"+n.round(e[1],2)+"H"+n.round(e[0],2)},hvh:function(t,e){return"H"+n.round((t[0]+e[0])/2,2)+"V"+n.round(e[1],2)+"H"+n.round(e[0],2)},vhv:function(t,e){return"V"+n.round((t[1]+e[1])/2,2)+"H"+n.round(e[0],2)+"V"+n.round(e[1],2)}},S=function(t,e){return"L"+n.round(e[0],2)+","+n.round(e[1],2)};y.steps=function(t){var e=C[t]||S;return function(t){for(var r="M"+n.round(t[0][0],2)+","+n.round(t[0][1],2),a=1;a<t.length;a++)r+=e(t[a-1],t[a]);return r}},y.makeTester=function(){var t=c.ensureSingleById(n.select("body"),"svg","js-plotly-tester",function(t){t.attr(f.svgAttrs).style({position:"absolute",left:"-10000px",top:"-10000px",width:"9000px",height:"9000px","z-index":"1"})}),e=c.ensureSingle(t,"path","js-reference-point",function(t){t.attr("d","M0,0H1V1H0Z").style({"stroke-width":0,fill:"black"})});y.tester=t,y.testref=e},y.savedBBoxes={};var O=0;function P(t){var e=t.getAttribute("data-unformatted");if(null!==e)return e+t.getAttribute("data-math")+t.getAttribute("text-anchor")+t.getAttribute("style")}y.bBox=function(t,e,r){var a,i,o;if(r||(r=P(t)),r){if(a=y.savedBBoxes[r])return c.extendFlat({},a)}else if(1===t.childNodes.length){var l=t.childNodes[0];if(r=P(l)){var s=+l.getAttribute("x")||0,f=+l.getAttribute("y")||0,d=l.getAttribute("transform");if(!d){var p=y.bBox(l,!1,r);return s&&(p.left+=s,p.right+=s),f&&(p.top+=f,p.bottom+=f),p}if(r+="~"+s+"~"+f+"~"+d,a=y.savedBBoxes[r])return c.extendFlat({},a)}}e?i=t:(o=y.tester.node(),i=t.cloneNode(!0),o.appendChild(i)),n.select(i).attr("transform",null).call(u.positionText,0,0);var h=i.getBoundingClientRect(),g=y.testref.node().getBoundingClientRect();e||o.removeChild(i);var v={height:h.height,width:h.width,left:h.left-g.left,top:h.top-g.top,right:h.right-g.left,bottom:h.bottom-g.top};return O>=1e4&&(y.savedBBoxes={},O=0),r&&(y.savedBBoxes[r]=v),O++,c.extendFlat({},v)},y.setClipUrl=function(t,e){if(e){if(void 0===y.baseUrl){var r=n.select("base");r.size()&&r.attr("href")?y.baseUrl=window.location.href.split("#")[0]:y.baseUrl=""}t.attr("clip-path","url("+y.baseUrl+"#"+e+")")}else t.attr("clip-path",null)},y.getTranslate=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||0,y:+e[1]||0}},y.setTranslate=function(t,e,r){var n=t.attr?"attr":"getAttribute",a=t.attr?"attr":"setAttribute",i=t[n]("transform")||"";return e=e||0,r=r||0,i=i.replace(/(\btranslate\(.*?\);?)/,"").trim(),i=(i+=" translate("+e+", "+r+")").trim(),t[a]("transform",i),i},y.getScale=function(t){var e=(t[t.attr?"attr":"getAttribute"]("transform")||"").replace(/.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,function(t,e,r){return[e,r].join(" ")}).split(" ");return{x:+e[0]||1,y:+e[1]||1}},y.setScale=function(t,e,r){var n=t.attr?"attr":"getAttribute",a=t.attr?"attr":"setAttribute",i=t[n]("transform")||"";return e=e||1,r=r||1,i=i.replace(/(\bscale\(.*?\);?)/,"").trim(),i=(i+=" scale("+e+", "+r+")").trim(),t[a]("transform",i),i};var D=/\s*sc.*/;y.setPointGroupScale=function(t,e,r){if(e=e||1,r=r||1,t){var n=1===e&&1===r?"":" scale("+e+","+r+")";t.each(function(){var t=(this.getAttribute("transform")||"").replace(D,"");t=(t+=n).trim(),this.setAttribute("transform",t)})}};var z=/translate\([^)]*\)\s*$/;y.setTextPointsScale=function(t,e,r){t&&t.each(function(){var t,a=n.select(this),i=a.select("text");if(i.node()){var o=parseFloat(i.attr("x")||0),l=parseFloat(i.attr("y")||0),s=(a.attr("transform")||"").match(z);t=1===e&&1===r?[]:["translate("+o+","+l+")","scale("+e+","+r+")","translate("+-o+","+-l+")"],s&&t.push(s),a.attr("transform",t.join(" "))}})}},{"../../constants/alignment":143,"../../constants/interactions":144,"../../constants/xmlns_namespaces":147,"../../lib":163,"../../lib/svg_text_utils":184,"../../registry":247,"../../traces/scatter/make_bubble_size_func":330,"../../traces/scatter/subtypes":336,"../color":45,"../colorscale":60,"./symbol_defs":71,d3:10,"fast-isnumeric":13,tinycolor2:28}],71:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,a="l"+e+",-"+e,i="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+a+i+a+i+o+i+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+e+","+n.round(t/2,2)+"H"+e+"L0,-"+n.round(t,2)+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+e+",-"+n.round(t/2,2)+"H"+e+"L0,"+n.round(t,2)+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M"+n.round(t/2,2)+",-"+e+"V"+e+"L-"+n.round(t,2)+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2);return"M-"+n.round(t/2,2)+",-"+e+"V"+e+"L"+n.round(t,2)+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),a=n.round(-t,2),i=n.round(-.309*t,2);return"M"+e+","+i+"L"+r+","+n.round(.809*t,2)+"H-"+r+"L-"+e+","+i+"L0,"+a+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),a=n.round(t*Math.sqrt(3)/2,2);return"M"+a+",-"+r+"V"+r+"L0,"+e+"L-"+a+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),a=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+a+"H"+r+"L"+e+",0L"+r+",-"+a+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),a=n.round(.951*e,2),i=n.round(.363*e,2),o=n.round(.588*e,2),l=n.round(-e,2),s=n.round(-.309*e,2),c=n.round(.118*e,2),u=n.round(.809*e,2);return"M"+r+","+s+"H"+a+"L"+i+","+c+"L"+o+","+u+"L0,"+n.round(.382*e,2)+"L-"+o+","+u+"L-"+i+","+c+"L-"+a+","+s+"H-"+r+"L0,"+l+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),a=n.round(.76*t,2);return"M-"+a+",0l-"+r+",-"+e+"h"+a+"l"+r+",-"+e+"l"+r+","+e+"h"+a+"l-"+r+","+e+"l"+r+","+e+"h-"+a+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+a+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),a=n.round(1.6*t,2),i=n.round(4*t,2),o="A "+i+","+i+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+a+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),a=n.round(1.6*t,2),i=n.round(4*t,2),o="A "+i+","+i+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+a+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),a="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+a+"-"+e+","+e+a+e+","+e+a+e+",-"+e+a+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),a="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+a+"0,"+e+a+e+",0"+a+"0,-"+e+a+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0,noFill:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0,noFill:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0,noFill:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0,noFill:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),a=n.round(.8*t,2);return"M-"+e+","+a+"L0,0M"+e+","+a+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),a=n.round(.8*t,2);return"M-"+e+",-"+a+"L0,0M"+e+",-"+a+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),a=n.round(.8*t,2);return"M"+a+","+e+"L0,0M"+a+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0,noFill:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),a=n.round(.8*t,2);return"M-"+a+","+e+"L0,0M-"+a+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0,noFill:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0,noFill:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0,noFill:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0,noFill:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0,noFill:!0}}},{d3:10}],72:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean",editType:"calc"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"],editType:"calc"},symmetric:{valType:"boolean",editType:"calc"},array:{valType:"data_array",editType:"calc"},arrayminus:{valType:"data_array",editType:"calc"},value:{valType:"number",min:0,dflt:10,editType:"calc"},valueminus:{valType:"number",min:0,dflt:10,editType:"calc"},traceref:{valType:"integer",min:0,dflt:0,editType:"style"},tracerefminus:{valType:"integer",min:0,dflt:0,editType:"style"},copy_ystyle:{valType:"boolean",editType:"plot"},copy_zstyle:{valType:"boolean",editType:"style"},color:{valType:"color",editType:"style"},thickness:{valType:"number",min:0,dflt:2,editType:"style"},width:{valType:"number",min:0,editType:"plot"},editType:"calc",_deprecated:{opacity:{valType:"number",editType:"style"}}}},{}],73:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../registry"),i=t("../../plots/cartesian/axes"),o=t("./compute_error");function l(t,e,r,a){var l=e["error_"+a]||{},s=[];if(l.visible&&-1!==["linear","log"].indexOf(r.type)){for(var c=o(l),u=0;u<t.length;u++){var f=t[u],d=f[a];if(n(r.c2l(d))){var p=c(d,u);if(n(p[0])&&n(p[1])){var h=f[a+"s"]=d-p[0],g=f[a+"h"]=d+p[1];s.push(h,g)}}}i.expand(r,s,{padded:!0})}}e.exports=function(t){for(var e=t.calcdata,r=0;r<e.length;r++){var n=e[r],o=n[0].trace;if(a.traceIs(o,"errorBarsOK")){var s=i.getFromId(t,o.xaxis),c=i.getFromId(t,o.yaxis);l(n,o,s,"x"),l(n,o,c,"y")}}}},{"../../plots/cartesian/axes":207,"../../registry":247,"./compute_error":74,"fast-isnumeric":13}],74:[function(t,e,r){"use strict";function n(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}e.exports=function(t){var e=t.type,r=t.symmetric;if("data"===e){var a=t.array||[];if(r)return function(t,e){var r=+a[e];return[r,r]};var i=t.arrayminus||[];return function(t,e){var r=+a[e],n=+i[e];return isNaN(r)&&isNaN(n)?[NaN,NaN]:[n||0,r||0]}}var o=n(e,t.value),l=n(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=o(t);return[e,e]}:function(t){return[l(t),o(t)]}}},{}],75:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../registry"),i=t("../../lib"),o=t("../../plot_api/plot_template"),l=t("./attributes");e.exports=function(t,e,r,s){var c="error_"+s.axis,u=o.newContainer(e,c),f=t[c]||{};function d(t,e){return i.coerce(f,u,l,t,e)}if(!1!==d("visible",void 0!==f.array||void 0!==f.value||"sqrt"===f.type)){var p=d("type","array"in f?"data":"percent"),h=!0;"sqrt"!==p&&(h=d("symmetric",!(("data"===p?"arrayminus":"valueminus")in f))),"data"===p?(d("array"),d("traceref"),h||(d("arrayminus"),d("tracerefminus"))):"percent"!==p&&"constant"!==p||(d("value"),h||d("valueminus"));var g="copy_"+s.inherit+"style";if(s.inherit)(e["error_"+s.inherit]||{}).visible&&d(g,!(f.color||n(f.thickness)||n(f.width)));s.inherit&&u[g]||(d("color",r),d("thickness"),d("width",a.traceIs(e,"gl3d")?0:4))}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../registry":247,"./attributes":72,"fast-isnumeric":13}],76:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plot_api/edit_types").overrideAll,i=t("./attributes"),o={error_x:n.extendFlat({},i),error_y:n.extendFlat({},i)};delete o.error_x.copy_zstyle,delete o.error_y.copy_zstyle,delete o.error_y.copy_ystyle;var l={error_x:n.extendFlat({},i),error_y:n.extendFlat({},i),error_z:n.extendFlat({},i)};delete l.error_x.copy_ystyle,delete l.error_y.copy_ystyle,delete l.error_z.copy_ystyle,delete l.error_z.copy_zstyle,e.exports={moduleType:"component",name:"errorbars",schema:{traces:{scatter:o,bar:o,histogram:o,scatter3d:a(l,"calc","nested"),scattergl:a(o,"calc","nested")}},supplyDefaults:t("./defaults"),calc:t("./calc"),makeComputeError:t("./compute_error"),plot:t("./plot"),style:t("./style"),hoverInfo:function(t,e,r){(e.error_y||{}).visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys));(e.error_x||{}).visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}}},{"../../lib":163,"../../plot_api/edit_types":190,"./attributes":72,"./calc":73,"./compute_error":74,"./defaults":75,"./plot":77,"./style":78}],77:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../drawing"),o=t("../../traces/scatter/subtypes");e.exports=function(t,e,r){var l=e.xaxis,s=e.yaxis,c=r&&r.duration>0;t.each(function(t){var u,f=t[0].trace,d=f.error_x||{},p=f.error_y||{};f.ids&&(u=function(t){return t.id});var h=o.hasMarkers(f)&&f.marker.maxdisplayed>0;p.visible||d.visible||(t=[]);var g=n.select(this).selectAll("g.errorbar").data(t,u);if(g.exit().remove(),t.length){d.visible||g.selectAll("path.xerror").remove(),p.visible||g.selectAll("path.yerror").remove(),g.style("opacity",1);var y=g.enter().append("g").classed("errorbar",!0);c&&y.style("opacity",0).transition().duration(r.duration).style("opacity",1),i.setClipUrl(g,e.layerClipId),g.each(function(t){var e=n.select(this),i=function(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0)));void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0)));return n}(t,l,s);if(!h||t.vis){var o,u=e.select("path.yerror");if(p.visible&&a(i.x)&&a(i.yh)&&a(i.ys)){var f=p.width;o="M"+(i.x-f)+","+i.yh+"h"+2*f+"m-"+f+",0V"+i.ys,i.noYS||(o+="m-"+f+",0h"+2*f),!u.size()?u=e.append("path").style("vector-effect","non-scaling-stroke").classed("yerror",!0):c&&(u=u.transition().duration(r.duration).ease(r.easing)),u.attr("d",o)}else u.remove();var g=e.select("path.xerror");if(d.visible&&a(i.y)&&a(i.xh)&&a(i.xs)){var y=(d.copy_ystyle?p:d).width;o="M"+i.xh+","+(i.y-y)+"v"+2*y+"m0,-"+y+"H"+i.xs,i.noXS||(o+="m0,-"+y+"v"+2*y),!g.size()?g=e.append("path").style("vector-effect","non-scaling-stroke").classed("xerror",!0):c&&(g=g.transition().duration(r.duration).ease(r.easing)),g.attr("d",o)}else g.remove()}})}})}},{"../../traces/scatter/subtypes":336,"../drawing":70,d3:10,"fast-isnumeric":13}],78:[function(t,e,r){"use strict";var n=t("d3"),a=t("../color");e.exports=function(t){t.each(function(t){var e=t[0].trace,r=e.error_y||{},i=e.error_x||{},o=n.select(this);o.selectAll("path.yerror").style("stroke-width",r.thickness+"px").call(a.stroke,r.color),i.copy_ystyle&&(i=r),o.selectAll("path.xerror").style("stroke-width",i.thickness+"px").call(a.stroke,i.color)})}},{"../color":45,d3:10}],79:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes");e.exports={hoverlabel:{bgcolor:{valType:"color",arrayOk:!0,editType:"none"},bordercolor:{valType:"color",arrayOk:!0,editType:"none"},font:n({arrayOk:!0,editType:"none"}),namelength:{valType:"integer",min:-1,arrayOk:!0,editType:"none"},editType:"calc"}}},{"../../plots/font_attributes":233}],80:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../registry");function i(t,e,r,a){a=a||n.identity,Array.isArray(t)&&(e[0][r]=a(t))}e.exports=function(t){var e=t.calcdata,r=t._fullLayout;function o(t){return function(e){return n.coerceHoverinfo({hoverinfo:e},{_module:t._module},r)}}for(var l=0;l<e.length;l++){var s=e[l],c=s[0].trace;if(!a.traceIs(c,"pie")){var u=a.traceIs(c,"2dMap")?i:n.fillArray;u(c.hoverinfo,s,"hi",o(c)),c.hoverlabel&&(u(c.hoverlabel.bgcolor,s,"hbg"),u(c.hoverlabel.bordercolor,s,"hbc"),u(c.hoverlabel.font.size,s,"hts"),u(c.hoverlabel.font.color,s,"htc"),u(c.hoverlabel.font.family,s,"htf"),u(c.hoverlabel.namelength,s,"hnl"))}}}},{"../../lib":163,"../../registry":247}],81:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("./hover").hover;e.exports=function(t,e,r){var i=n.getComponentMethod("annotations","onClick")(t,t._hoverdata);function o(){t.emit("plotly_click",{points:t._hoverdata,event:e})}void 0!==r&&a(t,e,r,!0),t._hoverdata&&e&&e.target&&(i&&i.then?i.then(o):o(),e.stopImmediatePropagation&&e.stopImmediatePropagation())}},{"../../registry":247,"./hover":85}],82:[function(t,e,r){"use strict";e.exports={YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:50,HOVERID:"-hover"}},{}],83:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./attributes"),i=t("./hoverlabel_defaults");e.exports=function(t,e,r,o){i(t,e,function(r,i){return n.coerce(t,e,a,r,i)},o.hoverlabel)}},{"../../lib":163,"./attributes":79,"./hoverlabel_defaults":86}],84:[function(t,e,r){"use strict";var n=t("../../lib");r.getSubplot=function(t){return t.subplot||t.xaxis+t.yaxis||t.geo},r.isTraceInSubplots=function(t,e){if("splom"===t.type){for(var n=t.xaxes||[],a=t.yaxes||[],i=0;i<n.length;i++)for(var o=0;o<a.length;o++)if(-1!==e.indexOf(n[i]+a[o]))return!0;return!1}return-1!==e.indexOf(r.getSubplot(t))},r.flat=function(t,e){for(var r=new Array(t.length),n=0;n<t.length;n++)r[n]=e;return r},r.p2c=function(t,e){for(var r=new Array(t.length),n=0;n<t.length;n++)r[n]=t[n].p2c(e);return r},r.getDistanceFunction=function(t,e,n,a){return"closest"===t?a||r.quadrature(e,n):"x"===t?e:n},r.getClosest=function(t,e,r){if(!1!==r.index)r.index>=0&&r.index<t.length?r.distance=0:r.index=!1;else for(var n=0;n<t.length;n++){var a=e(t[n]);a<=r.distance&&(r.index=n,r.distance=a)}return r},r.inbox=function(t,e,r){return t*e<0||0===t?r:1/0},r.quadrature=function(t,e){return function(r){var n=t(r),a=e(r);return Math.sqrt(n*n+a*a)}},r.makeEventData=function(t,e,n){var a="index"in t?t.index:t.pointNumber,i={data:e._input,fullData:e,curveNumber:e.index,pointNumber:a};if(e._indexToPoints){var o=e._indexToPoints[a];1===o.length?i.pointIndex=o[0]:i.pointIndices=o}else i.pointIndex=a;return e._module.eventData?i=e._module.eventData(i,t,e,n,a):("xVal"in t?i.x=t.xVal:"x"in t&&(i.x=t.x),"yVal"in t?i.y=t.yVal:"y"in t&&(i.y=t.y),t.xa&&(i.xaxis=t.xa),t.ya&&(i.yaxis=t.ya),void 0!==t.zLabelVal&&(i.z=t.zLabelVal)),r.appendArrayPointValue(i,e,a),i},r.appendArrayPointValue=function(t,e,r){var a=e._arrayAttrs;if(a)for(var l=0;l<a.length;l++){var s=a[l],c=i(s);if(void 0===t[c]){var u=o(n.nestedProperty(e,s).get(),r);void 0!==u&&(t[c]=u)}}},r.appendArrayMultiPointValues=function(t,e,r){var a=e._arrayAttrs;if(a)for(var l=0;l<a.length;l++){var s=a[l],c=i(s);if(void 0===t[c]){for(var u=n.nestedProperty(e,s).get(),f=new Array(r.length),d=0;d<r.length;d++)f[d]=o(u,r[d]);t[c]=f}}};var a={ids:"id",locations:"location",labels:"label",values:"value","marker.colors":"color"};function i(t){return a[t]||t}function o(t,e){return Array.isArray(e)?Array.isArray(t)&&Array.isArray(t[e[0]])?t[e[0]][e[1]]:void 0:t[e]}},{"../../lib":163}],85:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("tinycolor2"),o=t("../../lib"),l=t("../../lib/events"),s=t("../../lib/svg_text_utils"),c=t("../../lib/override_cursor"),u=t("../drawing"),f=t("../color"),d=t("../dragelement"),p=t("../../plots/cartesian/axes"),h=t("../../registry"),g=t("./helpers"),y=t("./constants"),v=y.YANGLE,m=Math.PI*v/180,x=1/Math.sin(m),b=Math.cos(m),_=Math.sin(m),w=y.HOVERARROWSIZE,k=y.HOVERTEXTPAD;function M(t,e,r){var a=e.hovermode,i=e.rotateLabels,l=e.bgColor,c=e.container,d=e.outerContainer,p=e.commonLabelOpts||{},h=e.fontFamily||y.HOVERFONT,g=e.fontSize||y.HOVERFONTSIZE,m=t[0],x=m.xa,b=m.ya,_="y"===a?"yLabel":"xLabel",M=m[_],T=(String(M)||"").split(" ")[0],A=d.node().getBoundingClientRect(),L=A.top,C=A.width,S=A.height,O=void 0!==M&&m.distance<=e.hoverdistance&&("x"===a||"y"===a);if(O){var P,D,z=!0;for(P=0;P<t.length;P++){z&&void 0===t[P].zLabel&&(z=!1),D=t[P].hoverinfo||t[P].trace.hoverinfo;var E=Array.isArray(D)?D:D.split("+");if(-1===E.indexOf("all")&&-1===E.indexOf(a)){O=!1;break}}z&&(O=!1)}var I=c.selectAll("g.axistext").data(O?[0]:[]);I.enter().append("g").classed("axistext",!0),I.exit().remove(),I.each(function(){var e=n.select(this),i=o.ensureSingle(e,"path","",function(t){t.style({"stroke-width":"1px"})}),l=o.ensureSingle(e,"text","",function(t){t.attr("data-notex",1)}),c=p.bgcolor||f.defaultLine,d=p.bordercolor||f.contrast(c);i.style({fill:c,stroke:d}),l.text(M).call(u.font,p.font.family||h,p.font.size||g,p.font.color||f.background).call(s.positionText,0,0).call(s.convertToTspans,r),e.attr("transform","");var y=l.node().getBoundingClientRect();if("x"===a){l.attr("text-anchor","middle").call(s.positionText,0,"top"===x.side?L-y.bottom-w-k:L-y.top+w+k);var v="top"===x.side?"-":"";i.attr("d","M0,0L"+w+","+v+w+"H"+(k+y.width/2)+"v"+v+(2*k+y.height)+"H-"+(k+y.width/2)+"V"+v+w+"H-"+w+"Z"),e.attr("transform","translate("+(x._offset+(m.x0+m.x1)/2)+","+(b._offset+("top"===x.side?0:b._length))+")")}else{l.attr("text-anchor","right"===b.side?"start":"end").call(s.positionText,("right"===b.side?1:-1)*(k+w),L-y.top-y.height/2);var A="right"===b.side?"":"-";i.attr("d","M0,0L"+A+w+","+w+"V"+(k+y.height/2)+"h"+A+(2*k+y.width)+"V-"+(k+y.height/2)+"H"+A+w+"V-"+w+"Z"),e.attr("transform","translate("+(x._offset+("right"===b.side?x._length:0))+","+(b._offset+(m.y0+m.y1)/2)+")")}t=t.filter(function(t){return void 0!==t.zLabelVal||(t[_]||"").split(" ")[0]===T})});var N=c.selectAll("g.hovertext").data(t,function(t){return[t.trace.index,t.index,t.x0,t.y0,t.name,t.attr,t.xa,t.ya||""].join(",")});return N.enter().append("g").classed("hovertext",!0).each(function(){var t=n.select(this);t.append("rect").call(f.fill,f.addOpacity(l,.8)),t.append("text").classed("name",!0),t.append("path").style("stroke-width","1px"),t.append("text").classed("nums",!0).call(u.font,h,g)}),N.exit().remove(),N.each(function(t){var e=n.select(this).attr("transform",""),o="",c="",d=f.opacity(t.color)?t.color:f.defaultLine,p=f.combine(d,l),y=t.borderColor||f.contrast(p);if(void 0!==t.nameOverride&&(t.name=t.nameOverride),t.name){o=s.plainText(t.name||"");var m=Math.round(t.nameLength);m>-1&&o.length>m&&(o=m>3?o.substr(0,m-3)+"...":o.substr(0,m))}void 0!==t.zLabel?(void 0!==t.xLabel&&(c+="x: "+t.xLabel+"<br>"),void 0!==t.yLabel&&(c+="y: "+t.yLabel+"<br>"),c+=(c?"z: ":"")+t.zLabel):O&&t[a+"Label"]===M?c=t[("x"===a?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(c=t.yLabel):c=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",!t.text&&0!==t.text||Array.isArray(t.text)||(c+=(c?"<br>":"")+t.text),void 0!==t.extraText&&(c+=(c?"<br>":"")+t.extraText),""===c&&(""===o&&e.remove(),c=o);var x=e.select("text.nums").call(u.font,t.fontFamily||h,t.fontSize||g,t.fontColor||y).text(c).attr("data-notex",1).call(s.positionText,0,0).call(s.convertToTspans,r),b=e.select("text.name"),_=0;o&&o!==c?(b.call(u.font,t.fontFamily||h,t.fontSize||g,p).text(o).attr("data-notex",1).call(s.positionText,0,0).call(s.convertToTspans,r),_=b.node().getBoundingClientRect().width+2*k):(b.remove(),e.select("rect").remove()),e.select("path").style({fill:p,stroke:y});var T,A,P=x.node().getBoundingClientRect(),D=t.xa._offset+(t.x0+t.x1)/2,z=t.ya._offset+(t.y0+t.y1)/2,E=Math.abs(t.x1-t.x0),I=Math.abs(t.y1-t.y0),N=P.width+w+k+_;t.ty0=L-P.top,t.bx=P.width+2*k,t.by=P.height+2*k,t.anchor="start",t.txwidth=P.width,t.tx2width=_,t.offset=0,i?(t.pos=D,T=z+I/2+N<=S,A=z-I/2-N>=0,"top"!==t.idealAlign&&T||!A?T?(z+=I/2,t.anchor="start"):t.anchor="middle":(z-=I/2,t.anchor="end")):(t.pos=z,T=D+E/2+N<=C,A=D-E/2-N>=0,"left"!==t.idealAlign&&T||!A?T?(D+=E/2,t.anchor="start"):t.anchor="middle":(D-=E/2,t.anchor="end")),x.attr("text-anchor",t.anchor),_&&b.attr("text-anchor",t.anchor),e.attr("transform","translate("+D+","+z+")"+(i?"rotate("+v+")":""))}),N}function T(t,e){t.each(function(t){var r=n.select(this);if(t.del)r.remove();else{var a="end"===t.anchor?-1:1,i=r.select("text.nums"),o={start:1,end:-1,middle:0}[t.anchor],l=o*(w+k),c=l+o*(t.txwidth+k),f=0,d=t.offset;"middle"===t.anchor&&(l-=t.tx2width/2,c+=t.txwidth/2+k),e&&(d*=-_,f=t.offset*b),r.select("path").attr("d","middle"===t.anchor?"M-"+(t.bx/2+t.tx2width/2)+","+(d-t.by/2)+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(a*w+f)+","+(w+d)+"v"+(t.by/2-w)+"h"+a*t.bx+"v-"+t.by+"H"+(a*w+f)+"V"+(d-w)+"Z"),i.call(s.positionText,l+f,d+t.ty0-t.by/2+k),t.tx2width&&(r.select("text.name").call(s.positionText,c+o*k+f,d+t.ty0-t.by/2+k),r.select("rect").call(u.setRect,c+(o-1)*t.tx2width/2+f,d-t.by/2-1,t.tx2width,t.by+2))}})}function A(t,e){var r=t.index,n=t.trace||{},a=t.cd[0],i=t.cd[r]||{},l=Array.isArray(r)?function(t,e){return o.castOption(a,r,t)||o.extractOption({},n,"",e)}:function(t,e){return o.extractOption(i,n,t,e)};function s(e,r,n){var a=l(r,n);a&&(t[e]=a)}if(s("hoverinfo","hi","hoverinfo"),s("color","hbg","hoverlabel.bgcolor"),s("borderColor","hbc","hoverlabel.bordercolor"),s("fontFamily","htf","hoverlabel.font.family"),s("fontSize","hts","hoverlabel.font.size"),s("fontColor","htc","hoverlabel.font.color"),s("nameLength","hnl","hoverlabel.namelength"),t.posref="y"===e?t.xa._offset+(t.x0+t.x1)/2:t.ya._offset+(t.y0+t.y1)/2,t.x0=o.constrain(t.x0,0,t.xa._length),t.x1=o.constrain(t.x1,0,t.xa._length),t.y0=o.constrain(t.y0,0,t.ya._length),t.y1=o.constrain(t.y1,0,t.ya._length),void 0!==t.xLabelVal&&(t.xLabel="xLabel"in t?t.xLabel:p.hoverLabelText(t.xa,t.xLabelVal),t.xVal=t.xa.c2d(t.xLabelVal)),void 0!==t.yLabelVal&&(t.yLabel="yLabel"in t?t.yLabel:p.hoverLabelText(t.ya,t.yLabelVal),t.yVal=t.ya.c2d(t.yLabelVal)),void 0!==t.zLabelVal&&void 0===t.zLabel&&(t.zLabel=String(t.zLabelVal)),!(isNaN(t.xerr)||"log"===t.xa.type&&t.xerr<=0)){var c=p.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+c+" / -"+p.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" \xb1 "+c,"x"===e&&(t.distance+=1)}if(!(isNaN(t.yerr)||"log"===t.ya.type&&t.yerr<=0)){var u=p.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+u+" / -"+p.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" \xb1 "+u,"y"===e&&(t.distance+=1)}var f=t.hoverinfo||t.trace.hoverinfo;return"all"!==f&&(-1===(f=Array.isArray(f)?f:f.split("+")).indexOf("x")&&(t.xLabel=void 0),-1===f.indexOf("y")&&(t.yLabel=void 0),-1===f.indexOf("z")&&(t.zLabel=void 0),-1===f.indexOf("text")&&(t.text=void 0),-1===f.indexOf("name")&&(t.name=void 0)),t}function L(t,e){var r,n,a=e.container,o=e.fullLayout,l=e.event,s=!!t.hLinePoint,c=!!t.vLinePoint;if(a.selectAll(".spikeline").remove(),c||s){var d=f.combine(o.plot_bgcolor,o.paper_bgcolor);if(s){var p,h,g=t.hLinePoint;r=g&&g.xa,"cursor"===(n=g&&g.ya).spikesnap?(p=l.pointerX,h=l.pointerY):(p=r._offset+g.x,h=n._offset+g.y);var y,v,m=i.readability(g.color,d)<1.5?f.contrast(d):g.color,x=n.spikemode,b=n.spikethickness,_=n.spikecolor||m,w=n._boundingBox,k=(w.left+w.right)/2<p?w.right:w.left;-1===x.indexOf("toaxis")&&-1===x.indexOf("across")||(-1!==x.indexOf("toaxis")&&(y=k,v=p),-1!==x.indexOf("across")&&(y=n._counterSpan[0],v=n._counterSpan[1]),a.insert("line",":first-child").attr({x1:y,x2:v,y1:h,y2:h,"stroke-width":b,stroke:_,"stroke-dasharray":u.dashStyle(n.spikedash,b)}).classed("spikeline",!0).classed("crisp",!0),a.insert("line",":first-child").attr({x1:y,x2:v,y1:h,y2:h,"stroke-width":b+2,stroke:d}).classed("spikeline",!0).classed("crisp",!0)),-1!==x.indexOf("marker")&&a.insert("circle",":first-child").attr({cx:k+("right"!==n.side?b:-b),cy:h,r:b,fill:_}).classed("spikeline",!0)}if(c){var M,T,A=t.vLinePoint;r=A&&A.xa,n=A&&A.ya,"cursor"===r.spikesnap?(M=l.pointerX,T=l.pointerY):(M=r._offset+A.x,T=n._offset+A.y);var L,C,S=i.readability(A.color,d)<1.5?f.contrast(d):A.color,O=r.spikemode,P=r.spikethickness,D=r.spikecolor||S,z=r._boundingBox,E=(z.top+z.bottom)/2<T?z.bottom:z.top;-1===O.indexOf("toaxis")&&-1===O.indexOf("across")||(-1!==O.indexOf("toaxis")&&(L=E,C=T),-1!==O.indexOf("across")&&(L=r._counterSpan[0],C=r._counterSpan[1]),a.insert("line",":first-child").attr({x1:M,x2:M,y1:L,y2:C,"stroke-width":P,stroke:D,"stroke-dasharray":u.dashStyle(r.spikedash,P)}).classed("spikeline",!0).classed("crisp",!0),a.insert("line",":first-child").attr({x1:M,x2:M,y1:L,y2:C,"stroke-width":P+2,stroke:d}).classed("spikeline",!0).classed("crisp",!0)),-1!==O.indexOf("marker")&&a.insert("circle",":first-child").attr({cx:M,cy:E-("top"!==r.side?P:-P),r:P,fill:D}).classed("spikeline",!0)}}}function C(t,e){return!e||(e.vLinePoint!==t._spikepoints.vLinePoint||e.hLinePoint!==t._spikepoints.hLinePoint)}r.hover=function(t,e,r,i){t=o.getGraphDiv(t),o.throttle(t._fullLayout._uid+y.HOVERID,y.HOVERMINTIME,function(){!function(t,e,r,i){r||(r="xy");var s=Array.isArray(r)?r:[r],u=t._fullLayout,y=u._plots||[],v=y[r],m=u._has("cartesian");if(v){var b=v.overlays.map(function(t){return t.id});s=s.concat(b)}for(var _=s.length,w=new Array(_),k=new Array(_),S=!1,O=0;O<_;O++){var P=s[O],D=y[P];if(D)S=!0,w[O]=p.getFromId(t,D.xaxis._id),k[O]=p.getFromId(t,D.yaxis._id);else{var z=u[P]._subplot;w[O]=z.xaxis,k[O]=z.yaxis}}var E=e.hovermode||u.hovermode;E&&!S&&(E="closest");if(-1===["x","y","closest"].indexOf(E)||!t.calcdata||t.querySelector(".zoombox")||t._dragging)return d.unhoverRaw(t,e);var I,N,R,F,j,B,H,q,V,U,G,Y,X,Z=-1===u.hoverdistance?1/0:u.hoverdistance,W=-1===u.spikedistance?1/0:u.spikedistance,Q=[],J=[],$={hLinePoint:null,vLinePoint:null};if(Array.isArray(e))for(E="array",R=0;R<e.length;R++)"skip"!==(j=t.calcdata[e[R].curveNumber||0])[0].trace.hoverinfo&&J.push(j);else{for(F=0;F<t.calcdata.length;F++)j=t.calcdata[F],"skip"!==(B=j[0].trace).hoverinfo&&g.isTraceInSubplots(B,s)&&J.push(j);var K,tt,et=!e.target;if(et)K="xpx"in e?e.xpx:w[0]._length/2,tt="ypx"in e?e.ypx:k[0]._length/2;else{if(!1===l.triggerHandler(t,"plotly_beforehover",e))return;var rt=e.target.getBoundingClientRect();if(K=e.clientX-rt.left,tt=e.clientY-rt.top,K<0||K>w[0]._length||tt<0||tt>k[0]._length)return d.unhoverRaw(t,e)}if(e.pointerX=K+w[0]._offset,e.pointerY=tt+k[0]._offset,I="xval"in e?g.flat(s,e.xval):g.p2c(w,K),N="yval"in e?g.flat(s,e.yval):g.p2c(k,tt),!a(I[0])||!a(N[0]))return o.warn("Fx.hover failed",e,t),d.unhoverRaw(t,e)}var nt=1/0;for(F=0;F<J.length;F++)if((j=J[F])&&j[0]&&j[0].trace&&!0===j[0].trace.visible&&(B=j[0].trace,-1===["carpet","contourcarpet"].indexOf(B._module.name))){if("splom"===B.type?H=s[q=0]:(H=g.getSubplot(B),q=s.indexOf(H)),V=E,Y={cd:j,trace:B,xa:w[q],ya:k[q],maxHoverDistance:Z,maxSpikeDistance:W,index:!1,distance:Math.min(nt,Z),spikeDistance:1/0,xSpike:void 0,ySpike:void 0,color:f.defaultLine,name:B.name,x0:void 0,x1:void 0,y0:void 0,y1:void 0,xLabelVal:void 0,yLabelVal:void 0,zLabelVal:void 0,text:void 0},u[H]&&(Y.subplot=u[H]._subplot),X=Q.length,"array"===V){var at=e[F];"pointNumber"in at?(Y.index=at.pointNumber,V="closest"):(V="","xval"in at&&(U=at.xval,V="x"),"yval"in at&&(G=at.yval,V=V?"closest":"y"))}else U=I[q],G=N[q];if(0!==Z)if(B._module&&B._module.hoverPoints){var it=B._module.hoverPoints(Y,U,G,V,u._hoverlayer);if(it)for(var ot,lt=0;lt<it.length;lt++)ot=it[lt],a(ot.x0)&&a(ot.y0)&&Q.push(A(ot,E))}else o.log("Unrecognized trace type in hover:",B);if("closest"===E&&Q.length>X&&(Q.splice(0,X),nt=Q[0].distance),m&&0!==W&&0===Q.length){Y.distance=W,Y.index=!1;var st=B._module.hoverPoints(Y,U,G,"closest",u._hoverlayer);if(st&&(st=st.filter(function(t){return t.spikeDistance<=W})),st&&st.length){var ct,ut=st.filter(function(t){return t.xa.showspikes});if(ut.length){var ft=ut[0];a(ft.x0)&&a(ft.y0)&&(ct=gt(ft),(!$.vLinePoint||$.vLinePoint.spikeDistance>ct.spikeDistance)&&($.vLinePoint=ct))}var dt=st.filter(function(t){return t.ya.showspikes});if(dt.length){var pt=dt[0];a(pt.x0)&&a(pt.y0)&&(ct=gt(pt),(!$.hLinePoint||$.hLinePoint.spikeDistance>ct.spikeDistance)&&($.hLinePoint=ct))}}}}function ht(t,e){for(var r,n=null,a=1/0,i=0;i<t.length;i++)(r=t[i].spikeDistance)<a&&r<=e&&(n=t[i],a=r);return n}function gt(t){return t?{xa:t.xa,ya:t.ya,x:void 0!==t.xSpike?t.xSpike:(t.x0+t.x1)/2,y:void 0!==t.ySpike?t.ySpike:(t.y0+t.y1)/2,distance:t.distance,spikeDistance:t.spikeDistance,curveNumber:t.trace.index,color:t.color,pointNumber:t.index}:null}var yt={fullLayout:u,container:u._hoverlayer,outerContainer:u._paperdiv,event:e},vt=t._spikepoints,mt={vLinePoint:$.vLinePoint,hLinePoint:$.hLinePoint};if(t._spikepoints=mt,m&&0!==W&&0!==Q.length){var xt=Q.filter(function(t){return t.ya.showspikes}),bt=ht(xt,W);$.hLinePoint=gt(bt);var _t=Q.filter(function(t){return t.xa.showspikes}),wt=ht(_t,W);$.vLinePoint=gt(wt)}if(0===Q.length){var kt=d.unhoverRaw(t,e);return!m||null===$.hLinePoint&&null===$.vLinePoint||C(vt)&&L($,yt),kt}m&&C(vt)&&L($,yt);Q.sort(function(t,e){return t.distance-e.distance});var Mt=t._hoverdata,Tt=[];for(R=0;R<Q.length;R++){var At=Q[R];Tt.push(g.makeEventData(At,At.trace,At.cd))}t._hoverdata=Tt;var Lt="y"===E&&J.length>1,Ct=f.combine(u.plot_bgcolor||f.background,u.paper_bgcolor),St={hovermode:E,rotateLabels:Lt,bgColor:Ct,container:u._hoverlayer,outerContainer:u._paperdiv,commonLabelOpts:u.hoverlabel,hoverdistance:u.hoverdistance},Ot=M(Q,St,t);if(function(t,e,r){var n,a,i,o,l,s,c,u=0,f=t.map(function(t,n){var a=t[e];return[{i:n,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===a._id.charAt(0)?x:1)/2,pmin:0,pmax:"x"===a._id.charAt(0)?r.width:r.height}]}).sort(function(t,e){return t[0].posref-e[0].posref});function d(t){var e=t[0],r=t[t.length-1];if(a=e.pmin-e.pos-e.dp+e.size,i=r.pos+r.dp+r.size-e.pmax,a>.01){for(l=t.length-1;l>=0;l--)t[l].dp+=a;n=!1}if(!(i<.01)){if(a<-.01){for(l=t.length-1;l>=0;l--)t[l].dp-=i;n=!1}if(n){var c=0;for(o=0;o<t.length;o++)(s=t[o]).pos+s.dp+s.size>e.pmax&&c++;for(o=t.length-1;o>=0&&!(c<=0);o--)(s=t[o]).pos>e.pmax-1&&(s.del=!0,c--);for(o=0;o<t.length&&!(c<=0);o++)if((s=t[o]).pos<e.pmin+1)for(s.del=!0,c--,i=2*s.size,l=t.length-1;l>=0;l--)t[l].dp-=i;for(o=t.length-1;o>=0&&!(c<=0);o--)(s=t[o]).pos+s.dp+s.size>e.pmax&&(s.del=!0,c--)}}}for(;!n&&u<=t.length;){for(u++,n=!0,o=0;o<f.length-1;){var p=f[o],h=f[o+1],g=p[p.length-1],y=h[0];if((a=g.pos+g.dp+g.size-y.pos-y.dp+y.size)>.01&&g.pmin===y.pmin&&g.pmax===y.pmax){for(l=h.length-1;l>=0;l--)h[l].dp+=a;for(p.push.apply(p,h),f.splice(o+1,1),c=0,l=p.length-1;l>=0;l--)c+=p[l].dp;for(i=c/p.length,l=p.length-1;l>=0;l--)p[l].dp-=i;n=!1}else o++}f.forEach(d)}for(o=f.length-1;o>=0;o--){var v=f[o];for(l=v.length-1;l>=0;l--){var m=v[l],b=t[m.i];b.offset=m.dp,b.del=m.del}}}(Q,Lt?"xa":"ya",u),T(Ot,Lt),e.target&&e.target.tagName){var Pt=h.getComponentMethod("annotations","hasClickToShow")(t,Tt);c(n.select(e.target),Pt?"pointer":"")}if(!e.target||i||!function(t,e,r){if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var a=r[n],i=t._hoverdata[n];if(a.curveNumber!==i.curveNumber||String(a.pointNumber)!==String(i.pointNumber))return!0}return!1}(t,0,Mt))return;Mt&&t.emit("plotly_unhover",{event:e,points:Mt});t.emit("plotly_hover",{event:e,points:t._hoverdata,xaxes:w,yaxes:k,xvals:I,yvals:N})}(t,e,r,i)})},r.loneHover=function(t,e){var r={color:t.color||f.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,borderColor:t.borderColor,fontFamily:t.fontFamily,fontSize:t.fontSize,fontColor:t.fontColor,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},a=n.select(e.container),i=e.outerContainer?n.select(e.outerContainer):a,o={hovermode:"closest",rotateLabels:!1,bgColor:e.bgColor||f.background,container:a,outerContainer:i},l=M([r],o,e.gd);return T(l,o.rotateLabels),l.node()}},{"../../lib":163,"../../lib/events":156,"../../lib/override_cursor":174,"../../lib/svg_text_utils":184,"../../plots/cartesian/axes":207,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"./constants":82,"./helpers":84,d3:10,"fast-isnumeric":13,tinycolor2:28}],86:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,a){r("hoverlabel.bgcolor",(a=a||{}).bgcolor),r("hoverlabel.bordercolor",a.bordercolor),r("hoverlabel.namelength",a.namelength),n.coerceFont(r,"hoverlabel.font",a.font)}},{"../../lib":163}],87:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../lib"),i=t("../dragelement"),o=t("./helpers"),l=t("./layout_attributes");e.exports={moduleType:"component",name:"fx",constants:t("./constants"),schema:{layout:l},attributes:t("./attributes"),layoutAttributes:l,supplyLayoutGlobalDefaults:t("./layout_global_defaults"),supplyDefaults:t("./defaults"),supplyLayoutDefaults:t("./layout_defaults"),calc:t("./calc"),getDistanceFunction:o.getDistanceFunction,getClosest:o.getClosest,inbox:o.inbox,quadrature:o.quadrature,appendArrayPointValue:o.appendArrayPointValue,castHoverOption:function(t,e,r){return a.castOption(t,e,"hoverlabel."+r)},castHoverinfo:function(t,e,r){return a.castOption(t,r,"hoverinfo",function(r){return a.coerceHoverinfo({hoverinfo:r},{_module:t._module},e)})},hover:t("./hover").hover,unhover:i.unhover,loneHover:t("./hover").loneHover,loneUnhover:function(t){var e=a.isD3Selection(t)?t:n.select(t);e.selectAll("g.hovertext").remove(),e.selectAll(".spikeline").remove()},click:t("./click")}},{"../../lib":163,"../dragelement":67,"./attributes":79,"./calc":80,"./click":81,"./constants":82,"./defaults":83,"./helpers":84,"./hover":85,"./layout_attributes":88,"./layout_defaults":89,"./layout_global_defaults":90,d3:10}],88:[function(t,e,r){"use strict";var n=t("./constants"),a=t("../../plots/font_attributes")({editType:"none"});a.family.dflt=n.HOVERFONT,a.size.dflt=n.HOVERFONTSIZE,e.exports={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom",editType:"modebar"},hovermode:{valType:"enumerated",values:["x","y","closest",!1],editType:"modebar"},hoverdistance:{valType:"integer",min:-1,dflt:20,editType:"none"},spikedistance:{valType:"integer",min:-1,dflt:20,editType:"none"},hoverlabel:{bgcolor:{valType:"color",editType:"none"},bordercolor:{valType:"color",editType:"none"},font:a,namelength:{valType:"integer",min:-1,dflt:15,editType:"none"},editType:"none"},selectdirection:{valType:"enumerated",values:["h","v","d","any"],dflt:"any",editType:"none"}}},{"../../plots/font_attributes":233,"./constants":82}],89:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./layout_attributes");e.exports=function(t,e,r){function i(r,i){return n.coerce(t,e,a,r,i)}var o;"select"===i("dragmode")&&i("selectdirection"),e._has("cartesian")?(e._isHoriz=function(t){for(var e=!0,r=0;r<t.length;r++){var n=t[r];if("h"!==n.orientation){e=!1;break}}return e}(r),o=e._isHoriz?"y":"x"):o="closest",i("hovermode",o)&&(i("hoverdistance"),i("spikedistance"));var l=e._has("mapbox"),s=e._has("geo"),c=e._basePlotModules.length;"zoom"===e.dragmode&&((l||s)&&1===c||l&&s&&2===c)&&(e.dragmode="pan")}},{"../../lib":163,"./layout_attributes":88}],90:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./hoverlabel_defaults"),i=t("./layout_attributes");e.exports=function(t,e){a(t,e,function(r,a){return n.coerce(t,e,i,r,a)})}},{"../../lib":163,"./hoverlabel_defaults":86,"./layout_attributes":88}],91:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../lib/regex").counter,i=t("../../plots/domain").attributes,o=t("../../plots/cartesian/constants").idRegex,l=t("../../plot_api/plot_template"),s={rows:{valType:"integer",min:1,editType:"plot"},roworder:{valType:"enumerated",values:["top to bottom","bottom to top"],dflt:"top to bottom",editType:"plot"},columns:{valType:"integer",min:1,editType:"plot"},subplots:{valType:"info_array",freeLength:!0,dimensions:2,items:{valType:"enumerated",values:[a("xy").toString(),""],editType:"plot"},editType:"plot"},xaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[o.x.toString(),""],editType:"plot"},editType:"plot"},yaxes:{valType:"info_array",freeLength:!0,items:{valType:"enumerated",values:[o.y.toString(),""],editType:"plot"},editType:"plot"},pattern:{valType:"enumerated",values:["independent","coupled"],dflt:"coupled",editType:"plot"},xgap:{valType:"number",min:0,max:1,editType:"plot"},ygap:{valType:"number",min:0,max:1,editType:"plot"},domain:i({name:"grid",editType:"plot",noGridCell:!0},{}),xside:{valType:"enumerated",values:["bottom","bottom plot","top plot","top"],dflt:"bottom plot",editType:"plot"},yside:{valType:"enumerated",values:["left","left plot","right plot","right"],dflt:"left plot",editType:"plot"},editType:"plot"};function c(t,e,r){var n=e[r+"axes"],a=Object.keys((t._splomAxes||{})[r]||{});return Array.isArray(n)?n:a.length?a:void 0}function u(t,e,r,n,a,i){var o=e(t+"gap",r),l=e("domain."+t);e(t+"side",n);for(var s=new Array(a),c=l[0],u=(l[1]-c)/(a-o),f=u*(1-o),d=0;d<a;d++){var p=c+u*d;s[i?a-1-d:d]=[p,p+f]}return s}function f(t,e,r,n,a){var i,o=new Array(r);function l(t,r){-1!==e.indexOf(r)&&void 0===n[r]?(o[t]=r,n[r]=t):o[t]=""}if(Array.isArray(t))for(i=0;i<r;i++)l(i,t[i]);else for(l(0,a),i=1;i<r;i++)l(i,a+(i+1));return o}e.exports={moduleType:"component",name:"grid",schema:{layout:{grid:s}},layoutAttributes:s,sizeDefaults:function(t,e){var r=t.grid||{},a=c(e,r,"x"),i=c(e,r,"y");if(t.grid||a||i){var o,f,d=Array.isArray(r.subplots)&&Array.isArray(r.subplots[0]),p=Array.isArray(a),h=Array.isArray(i),g=p&&a!==r.xaxes&&h&&i!==r.yaxes;d?(o=r.subplots.length,f=r.subplots[0].length):(h&&(o=i.length),p&&(f=a.length));var y=l.newContainer(e,"grid"),v=M("rows",o),m=M("columns",f);if(v*m>1){d||p||h||"independent"===M("pattern")&&(d=!0),y._hasSubplotGrid=d;var x,b,_="top to bottom"===M("roworder"),w=d?.2:.1,k=d?.3:.1;g&&e._splomGridDflt&&(x=e._splomGridDflt.xside,b=e._splomGridDflt.yside),y._domains={x:u("x",M,w,x,m),y:u("y",M,k,b,v,_)}}else delete e.grid}function M(t,e){return n.coerce(r,y,s,t,e)}},contentDefaults:function(t,e){var r=e.grid;if(r&&r._domains){var n,a,i,o,l,s,u,d=t.grid||{},p=e._subplots,h=r._hasSubplotGrid,g=r.rows,y=r.columns,v="independent"===r.pattern,m=r._axisMap={};if(h){var x=d.subplots||[];s=r.subplots=new Array(g);var b=1;for(n=0;n<g;n++){var _=s[n]=new Array(y),w=x[n]||[];for(a=0;a<y;a++)if(v?(l=1===b?"xy":"x"+b+"y"+b,b++):l=w[a],_[a]="",-1!==p.cartesian.indexOf(l)){if(u=l.indexOf("y"),i=l.slice(0,u),o=l.slice(u),void 0!==m[i]&&m[i]!==a||void 0!==m[o]&&m[o]!==n)continue;_[a]=l,m[i]=a,m[o]=n}}}else{var k=c(e,d,"x"),M=c(e,d,"y");r.xaxes=f(k,p.xaxis,y,m,"x"),r.yaxes=f(M,p.yaxis,g,m,"y")}var T=r._anchors={},A="top to bottom"===r.roworder;for(var L in m){var C,S,O,P=L.charAt(0),D=r[P+"side"];if(D.length<8)T[L]="free";else if("x"===P){if("t"===D.charAt(0)===A?(C=0,S=1,O=g):(C=g-1,S=-1,O=-1),h){var z=m[L];for(n=C;n!==O;n+=S)if((l=s[n][z])&&(u=l.indexOf("y"),l.slice(0,u)===L)){T[L]=l.slice(u);break}}else for(n=C;n!==O;n+=S)if(o=r.yaxes[n],-1!==p.cartesian.indexOf(L+o)){T[L]=o;break}}else if("l"===D.charAt(0)?(C=0,S=1,O=y):(C=y-1,S=-1,O=-1),h){var E=m[L];for(n=C;n!==O;n+=S)if((l=s[E][n])&&(u=l.indexOf("y"),l.slice(u)===L)){T[L]=l.slice(0,u);break}}else for(n=C;n!==O;n+=S)if(i=r.xaxes[n],-1!==p.cartesian.indexOf(i+L)){T[L]=i;break}}}}}},{"../../lib":163,"../../lib/regex":178,"../../plot_api/plot_template":197,"../../plots/cartesian/constants":212,"../../plots/domain":232}],92:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/constants"),a=t("../../plot_api/plot_template").templatedArray;e.exports=a("image",{visible:{valType:"boolean",dflt:!0,editType:"arraydraw"},source:{valType:"string",editType:"arraydraw"},layer:{valType:"enumerated",values:["below","above"],dflt:"above",editType:"arraydraw"},sizex:{valType:"number",dflt:0,editType:"arraydraw"},sizey:{valType:"number",dflt:0,editType:"arraydraw"},sizing:{valType:"enumerated",values:["fill","contain","stretch"],dflt:"contain",editType:"arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},x:{valType:"any",dflt:0,editType:"arraydraw"},y:{valType:"any",dflt:0,editType:"arraydraw"},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left",editType:"arraydraw"},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"top",editType:"arraydraw"},xref:{valType:"enumerated",values:["paper",n.idRegex.x.toString()],dflt:"paper",editType:"arraydraw"},yref:{valType:"enumerated",values:["paper",n.idRegex.y.toString()],dflt:"paper",editType:"arraydraw"},editType:"arraydraw"})},{"../../plot_api/plot_template":197,"../../plots/cartesian/constants":212}],93:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib/to_log_range");e.exports=function(t,e,r,i){e=e||{};var o="log"===r&&"linear"===e.type,l="linear"===r&&"log"===e.type;if(o||l)for(var s,c,u=t._fullLayout.images,f=e._id.charAt(0),d=0;d<u.length;d++)if(c="images["+d+"].",(s=u[d])[f+"ref"]===e._id){var p=s[f],h=s["size"+f],g=null,y=null;if(o){g=a(p,e.range);var v=h/Math.pow(10,g)/2;y=2*Math.log(v+Math.sqrt(1+v*v))/Math.LN10}else y=(g=Math.pow(10,p))*(Math.pow(10,h/2)-Math.pow(10,-h/2));n(g)?n(y)||(y=null):(g=null,y=null),i(c+f,g),i(c+"size"+f,y)}}},{"../../lib/to_log_range":186,"fast-isnumeric":13}],94:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../../plots/array_container_defaults"),o=t("./attributes");function l(t,e,r){function i(r,a){return n.coerce(t,e,o,r,a)}var l=i("source");if(!i("visible",!!l))return e;i("layer"),i("xanchor"),i("yanchor"),i("sizex"),i("sizey"),i("sizing"),i("opacity");for(var s={_fullLayout:r},c=["x","y"],u=0;u<2;u++){var f=c[u],d=a.coerceRef(t,e,s,f,"paper");a.coercePosition(e,s,i,d,f,0)}return e}e.exports=function(t,e){i(t,e,{name:"images",handleItemDefaults:l})}},{"../../lib":163,"../../plots/array_container_defaults":203,"../../plots/cartesian/axes":207,"./attributes":92}],95:[function(t,e,r){"use strict";var n=t("d3"),a=t("../drawing"),i=t("../../plots/cartesian/axes"),o=t("../../constants/xmlns_namespaces");e.exports=function(t){var e,r,l=t._fullLayout,s=[],c={},u=[];for(r=0;r<l.images.length;r++){var f=l.images[r];if(f.visible)if("below"===f.layer&&"paper"!==f.xref&&"paper"!==f.yref){e=f.xref+f.yref;var d=l._plots[e];if(!d){u.push(f);continue}d.mainplot&&(e=d.mainplot.id),c[e]||(c[e]=[]),c[e].push(f)}else"above"===f.layer?s.push(f):u.push(f)}var p={x:{left:{sizing:"xMin",offset:0},center:{sizing:"xMid",offset:-.5},right:{sizing:"xMax",offset:-1}},y:{top:{sizing:"YMin",offset:0},middle:{sizing:"YMid",offset:-.5},bottom:{sizing:"YMax",offset:-1}}};function h(e){var r=n.select(this);if(!this.img||this.img.src!==e.source){r.attr("xmlns",o.svg);var a=new Promise(function(t){var n=new Image;function a(){r.remove(),t()}this.img=n,n.setAttribute("crossOrigin","anonymous"),n.onerror=a,n.onload=function(){var e=document.createElement("canvas");e.width=this.width,e.height=this.height,e.getContext("2d").drawImage(this,0,0);var n=e.toDataURL("image/png");r.attr("xlink:href",n),t()},r.on("error",a),n.src=e.source}.bind(this));t._promises.push(a)}}function g(e){var r=n.select(this),o=i.getFromId(t,e.xref),s=i.getFromId(t,e.yref),c=l._size,u=o?Math.abs(o.l2p(e.sizex)-o.l2p(0)):e.sizex*c.w,f=s?Math.abs(s.l2p(e.sizey)-s.l2p(0)):e.sizey*c.h,d=u*p.x[e.xanchor].offset,h=f*p.y[e.yanchor].offset,g=p.x[e.xanchor].sizing+p.y[e.yanchor].sizing,y=(o?o.r2p(e.x)+o._offset:e.x*c.w+c.l)+d,v=(s?s.r2p(e.y)+s._offset:c.h-e.y*c.h+c.t)+h;switch(e.sizing){case"fill":g+=" slice";break;case"stretch":g="none"}r.attr({x:y,y:v,width:u,height:f,preserveAspectRatio:g,opacity:e.opacity});var m=(o?o._id:"")+(s?s._id:"");r.call(a.setClipUrl,m?"clip"+l._uid+m:null)}var y=l._imageLowerLayer.selectAll("image").data(u),v=l._imageUpperLayer.selectAll("image").data(s);y.enter().append("image"),v.enter().append("image"),y.exit().remove(),v.exit().remove(),y.each(function(t){h.bind(this)(t),g.bind(this)(t)}),v.each(function(t){h.bind(this)(t),g.bind(this)(t)});var m=Object.keys(l._plots);for(r=0;r<m.length;r++){e=m[r];var x=l._plots[e];if(x.imagelayer){var b=x.imagelayer.selectAll("image").data(c[e]||[]);b.enter().append("image"),b.exit().remove(),b.each(function(t){h.bind(this)(t),g.bind(this)(t)})}}}},{"../../constants/xmlns_namespaces":147,"../../plots/cartesian/axes":207,"../drawing":70,d3:10}],96:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"images",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("images"),draw:t("./draw"),convertCoords:t("./convert_coords")}},{"../../plots/cartesian/include_components":217,"./attributes":92,"./convert_coords":93,"./defaults":94,"./draw":95}],97:[function(t,e,r){"use strict";r.isRightAnchor=function(t){return"right"===t.xanchor||"auto"===t.xanchor&&t.x>=2/3},r.isCenterAnchor=function(t){return"center"===t.xanchor||"auto"===t.xanchor&&t.x>1/3&&t.x<2/3},r.isBottomAnchor=function(t){return"bottom"===t.yanchor||"auto"===t.yanchor&&t.y<=1/3},r.isMiddleAnchor=function(t){return"middle"===t.yanchor||"auto"===t.yanchor&&t.y>1/3&&t.y<2/3}},{}],98:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),a=t("../color/attributes");e.exports={bgcolor:{valType:"color",editType:"legend"},bordercolor:{valType:"color",dflt:a.defaultLine,editType:"legend"},borderwidth:{valType:"number",min:0,dflt:0,editType:"legend"},font:n({editType:"legend"}),orientation:{valType:"enumerated",values:["v","h"],dflt:"v",editType:"legend"},traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"],editType:"legend"},tracegroupgap:{valType:"number",min:0,dflt:10,editType:"legend"},x:{valType:"number",min:-2,max:3,dflt:1.02,editType:"legend"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"legend"},y:{valType:"number",min:-2,max:3,dflt:1,editType:"legend"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"legend"},editType:"legend"}},{"../../plots/font_attributes":233,"../color/attributes":44}],99:[function(t,e,r){"use strict";e.exports={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],100:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("../../plot_api/plot_template"),o=t("./attributes"),l=t("../../plots/layout_attributes"),s=t("./helpers");e.exports=function(t,e,r){for(var c,u,f,d,p=t.legend||{},h=0,g="normal",y=0;y<r.length;y++){var v=r[y];s.legendGetsTrace(v)&&(h++,n.traceIs(v,"pie")&&h++),(n.traceIs(v,"bar")&&"stack"===e.barmode||-1!==["tonextx","tonexty"].indexOf(v.fill))&&(g=s.isGrouped({traceorder:g})?"grouped+reversed":"reversed"),void 0!==v.legendgroup&&""!==v.legendgroup&&(g=s.isReversed({traceorder:g})?"reversed+grouped":"grouped")}if(!1!==a.coerce(t,e,l,"showlegend",h>1)){var m=i.newContainer(e,"legend");if(b("bgcolor",e.paper_bgcolor),b("bordercolor"),b("borderwidth"),a.coerceFont(b,"font",e.font),b("orientation"),"h"===m.orientation){var x=t.xaxis;x&&x.rangeslider&&x.rangeslider.visible?(c=0,f="left",u=1.1,d="bottom"):(c=0,f="left",u=-.1,d="top")}b("traceorder",g),s.isGrouped(e.legend)&&b("tracegroupgap"),b("x",c),b("xanchor",f),b("y",u),b("yanchor",d),a.noneOrAll(p,m,["x","y"])}function b(t,e){return a.coerce(p,m,o,t,e)}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../plots/layout_attributes":237,"../../registry":247,"./attributes":98,"./helpers":104}],101:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../lib"),i=t("../../plots/plots"),o=t("../../registry"),l=t("../../lib/events"),s=t("../dragelement"),c=t("../drawing"),u=t("../color"),f=t("../../lib/svg_text_utils"),d=t("./handle_click"),p=t("./constants"),h=t("../../constants/interactions"),g=t("../../constants/alignment"),y=g.LINE_SPACING,v=g.FROM_TL,m=g.FROM_BR,x=t("./get_legend_data"),b=t("./style"),_=t("./helpers"),w=t("./anchor_utils"),k=h.DBLCLICKDELAY;function M(t,e,r,n,a){var i=r.data()[0][0].trace,o={event:a,node:r.node(),curveNumber:i.index,expandedIndex:i._expandedIndex,data:t.data,layout:t.layout,frames:t._transitionData._frames,config:t._context,fullData:t._fullData,fullLayout:t._fullLayout};if(i._group&&(o.group=i._group),"pie"===i.type&&(o.label=r.datum()[0].label),!1!==l.triggerHandler(t,"plotly_legendclick",o))if(1===n)e._clickTimeout=setTimeout(function(){d(r,t,n)},k);else if(2===n){e._clickTimeout&&clearTimeout(e._clickTimeout),t._legendMouseDownTime=0,!1!==l.triggerHandler(t,"plotly_legenddoubleclick",o)&&d(r,t,n)}}function T(t,e,r){var n=t.data()[0][0],i=e._fullLayout,l=n.trace,s=o.traceIs(l,"pie"),u=l.index,d=s?n.label:l.name,p=e._context.edits.legendText&&!s,h=a.ensureSingle(t,"text","legendtext");function g(r){f.convertToTspans(r,e,function(){!function(t,e){var r=t.data()[0][0];if(!r.trace.showlegend)return void t.remove();var n,a,i=t.select("g[class*=math-group]"),o=i.node(),l=e._fullLayout.legend.font.size*y;if(o){var s=c.bBox(o);n=s.height,a=s.width,c.setTranslate(i,0,n/4)}else{var u=t.select(".legendtext"),d=f.lineCount(u),p=u.node();n=l*d,a=p?c.bBox(p).width:0;var h=l*(.3+(1-d)/2);f.positionText(u,40,h)}n=Math.max(n,16)+3,r.height=n,r.width=a}(t,e)})}h.attr("text-anchor","start").classed("user-select-none",!0).call(c.font,i.legend.font).text(p?A(d,r):d),p?h.call(f.makeEditable,{gd:e,text:d}).call(g).on("edit",function(t){this.text(A(t,r)).call(g);var i=n.trace._fullInput||{},l={};if(o.hasTransform(i,"groupby")){var s=o.getTransformIndices(i,"groupby"),c=s[s.length-1],f=a.keyedContainer(i,"transforms["+c+"].styles","target","value.name");f.set(n.trace._group,t),l=f.constructUpdate()}else l.name=t;return o.call("restyle",e,l,u)}):g(h)}function A(t,e){var r=Math.max(4,e);if(t&&t.trim().length>=r/2)return t;for(var n=r-(t=t||"").length;n>0;n--)t+=" ";return t}function L(t,e){var r,i=1,o=a.ensureSingle(t,"rect","legendtoggle",function(t){t.style("cursor","pointer").attr("pointer-events","all").call(u.fill,"rgba(0,0,0,0)")});o.on("mousedown",function(){(r=(new Date).getTime())-e._legendMouseDownTime<k?i+=1:(i=1,e._legendMouseDownTime=r)}),o.on("mouseup",function(){if(!e._dragged&&!e._editing){var r=e._fullLayout.legend;(new Date).getTime()-e._legendMouseDownTime>k&&(i=Math.max(i-1,1)),M(e,r,t,i,n.event)}})}function C(t,e,r){var a=t._fullLayout,i=a.legend,o=i.borderwidth,l=_.isGrouped(i),s=0;if(i._width=0,i._height=0,_.isVertical(i))l&&e.each(function(t,e){c.setTranslate(this,0,e*i.tracegroupgap)}),r.each(function(t){var e=t[0],r=e.height,n=e.width;c.setTranslate(this,o,5+o+i._height+r/2),i._height+=r,i._width=Math.max(i._width,n)}),i._width+=45+2*o,i._height+=10+2*o,l&&(i._height+=(i._lgroupsLength-1)*i.tracegroupgap),s=40;else if(l){for(var u=[i._width],f=e.data(),d=0,p=f.length;d<p;d++){var h=f[d].map(function(t){return t[0].width}),g=40+Math.max.apply(null,h);i._width+=i.tracegroupgap+g,u.push(i._width)}e.each(function(t,e){c.setTranslate(this,u[e],0)}),e.each(function(){var t=n.select(this).selectAll("g.traces"),e=0;t.each(function(t){var r=t[0].height;c.setTranslate(this,0,5+o+e+r/2),e+=r}),i._height=Math.max(i._height,e)}),i._height+=10+2*o,i._width+=2*o}else{var y,v=0,m=0,x=0,b=0,w=0,k=i.tracegroupgap||5;r.each(function(t){x=Math.max(40+t[0].width,x),w+=40+t[0].width+k}),y=a.width-(a.margin.r+a.margin.l)>o+w-k,r.each(function(t){var e=t[0],r=y?40+t[0].width:x;o+b+k+r>a.width-(a.margin.r+a.margin.l)&&(b=0,v+=m,i._height=i._height+m,m=0),c.setTranslate(this,o+b,5+o+e.height/2+v),i._width+=k+r,i._height=Math.max(i._height,e.height),b+=k+r,m=Math.max(e.height,m)}),i._width+=2*o,i._height+=10+2*o}i._width=Math.ceil(i._width),i._height=Math.ceil(i._height),r.each(function(e){var r=e[0],a=n.select(this).select(".legendtoggle");c.setRect(a,0,-r.height/2,(t._context.edits.legendText?0:i._width)+s,r.height)})}function S(t){var e=t._fullLayout.legend,r="left";w.isRightAnchor(e)?r="right":w.isCenterAnchor(e)&&(r="center");var n="top";w.isBottomAnchor(e)?n="bottom":w.isMiddleAnchor(e)&&(n="middle"),i.autoMargin(t,"legend",{x:e.x,y:e.y,l:e._width*v[r],r:e._width*m[r],b:e._height*m[n],t:e._height*v[n]})}e.exports=function(t){var e=t._fullLayout,r="legend"+e._uid;if(e._infolayer&&t.calcdata){t._legendMouseDownTime||(t._legendMouseDownTime=0);var l=e.legend,f=e.showlegend&&x(t.calcdata,l),d=e.hiddenlabels||[];if(!e.showlegend||!f.length)return e._infolayer.selectAll(".legend").remove(),e._topdefs.select("#"+r).remove(),void i.autoMargin(t,"legend");for(var h=0,g=0;g<f.length;g++)for(var y=0;y<f[g].length;y++){var _=f[g][y][0],k=_.trace,A=o.traceIs(k,"pie")?_.label:k.name;h=Math.max(h,A&&A.length||0)}var O=!1,P=a.ensureSingle(e._infolayer,"g","legend",function(t){t.attr("pointer-events","all"),O=!0}),D=a.ensureSingleById(e._topdefs,"clipPath",r,function(t){t.append("rect")}),z=a.ensureSingle(P,"rect","bg",function(t){t.attr("shape-rendering","crispEdges")});z.call(u.stroke,l.bordercolor).call(u.fill,l.bgcolor).style("stroke-width",l.borderwidth+"px");var E=a.ensureSingle(P,"g","scrollbox"),I=a.ensureSingle(P,"rect","scrollbar",function(t){t.attr({rx:20,ry:3,width:0,height:0}).call(u.fill,"#808BA4")}),N=E.selectAll("g.groups").data(f);N.enter().append("g").attr("class","groups"),N.exit().remove();var R=N.selectAll("g.traces").data(a.identity);R.enter().append("g").attr("class","traces"),R.exit().remove(),R.call(b,t).style("opacity",function(t){var e=t[0].trace;return o.traceIs(e,"pie")?-1!==d.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(){n.select(this).call(T,t,h).call(L,t)}),O&&(C(t,N,R),S(t));var F=e.width,j=e.height;C(t,N,R),l._height>j?function(t){var e=t._fullLayout.legend,r="left";w.isRightAnchor(e)?r="right":w.isCenterAnchor(e)&&(r="center");i.autoMargin(t,"legend",{x:e.x,y:.5,l:e._width*v[r],r:e._width*m[r],b:0,t:0})}(t):S(t);var B=e._size,H=B.l+B.w*l.x,q=B.t+B.h*(1-l.y);w.isRightAnchor(l)?H-=l._width:w.isCenterAnchor(l)&&(H-=l._width/2),w.isBottomAnchor(l)?q-=l._height:w.isMiddleAnchor(l)&&(q-=l._height/2);var V=l._width,U=B.w;V>U?(H=B.l,V=U):(H+V>F&&(H=F-V),H<0&&(H=0),V=Math.min(F-H,l._width));var G,Y,X,Z,W=l._height,Q=B.h;if(W>Q?(q=B.t,W=Q):(q+W>j&&(q=j-W),q<0&&(q=0),W=Math.min(j-q,l._height)),c.setTranslate(P,H,q),I.on(".drag",null),P.on("wheel",null),l._height<=W||t._context.staticPlot)z.attr({width:V-l.borderwidth,height:W-l.borderwidth,x:l.borderwidth/2,y:l.borderwidth/2}),c.setTranslate(E,0,0),D.select("rect").attr({width:V-2*l.borderwidth,height:W-2*l.borderwidth,x:l.borderwidth,y:l.borderwidth}),c.setClipUrl(E,r),c.setRect(I,0,0,0,0),delete l._scrollY;else{var J,$,K=Math.max(p.scrollBarMinHeight,W*W/l._height),tt=W-K-2*p.scrollBarMargin,et=l._height-W,rt=tt/et,nt=Math.min(l._scrollY||0,et);z.attr({width:V-2*l.borderwidth+p.scrollBarWidth+p.scrollBarMargin,height:W-l.borderwidth,x:l.borderwidth/2,y:l.borderwidth/2}),D.select("rect").attr({width:V-2*l.borderwidth+p.scrollBarWidth+p.scrollBarMargin,height:W-2*l.borderwidth,x:l.borderwidth,y:l.borderwidth+nt}),c.setClipUrl(E,r),it(nt,K,rt),P.on("wheel",function(){it(nt=a.constrain(l._scrollY+n.event.deltaY/tt*et,0,et),K,rt),0!==nt&&nt!==et&&n.event.preventDefault()});var at=n.behavior.drag().on("dragstart",function(){J=n.event.sourceEvent.clientY,$=nt}).on("drag",function(){var t=n.event.sourceEvent;2===t.buttons||t.ctrlKey||it(nt=a.constrain((t.clientY-J)/rt+$,0,et),K,rt)});I.call(at)}if(t._context.edits.legendPosition)P.classed("cursor-move",!0),s.init({element:P.node(),gd:t,prepFn:function(){var t=c.getTranslate(P);X=t.x,Z=t.y},moveFn:function(t,e){var r=X+t,n=Z+e;c.setTranslate(P,r,n),G=s.align(r,0,B.l,B.l+B.w,l.xanchor),Y=s.align(n,0,B.t+B.h,B.t,l.yanchor)},doneFn:function(){void 0!==G&&void 0!==Y&&o.call("relayout",t,{"legend.x":G,"legend.y":Y})},clickFn:function(r,n){var a=e._infolayer.selectAll("g.traces").filter(function(){var t=this.getBoundingClientRect();return n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom});a.size()>0&&M(t,P,a,r,n)}})}function it(e,r,n){l._scrollY=t._fullLayout.legend._scrollY=e,c.setTranslate(E,0,-e),c.setRect(I,V,p.scrollBarMargin+e*n,p.scrollBarWidth,r),D.select("rect").attr({y:l.borderwidth+e})}}},{"../../constants/alignment":143,"../../constants/interactions":144,"../../lib":163,"../../lib/events":156,"../../lib/svg_text_utils":184,"../../plots/plots":239,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"./anchor_utils":97,"./constants":99,"./get_legend_data":102,"./handle_click":103,"./helpers":104,"./style":106,d3:10}],102:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("./helpers");e.exports=function(t,e){var r,i,o={},l=[],s=!1,c={},u=0;function f(t,r){if(""!==t&&a.isGrouped(e))-1===l.indexOf(t)?(l.push(t),s=!0,o[t]=[[r]]):o[t].push([r]);else{var n="~~i"+u;l.push(n),o[n]=[[r]],u++}}for(r=0;r<t.length;r++){var d=t[r],p=d[0],h=p.trace,g=h.legendgroup;if(a.legendGetsTrace(h)&&h.showlegend)if(n.traceIs(h,"pie"))for(c[g]||(c[g]={}),i=0;i<d.length;i++){var y=d[i].label;c[g][y]||(f(g,{label:y,color:d[i].color,i:d[i].i,trace:h}),c[g][y]=!0)}else f(g,p)}if(!l.length)return[];var v,m,x=l.length;if(s&&a.isGrouped(e))for(m=new Array(x),r=0;r<x;r++)v=o[l[r]],m[r]=a.isReversed(e)?v.reverse():v;else{for(m=[new Array(x)],r=0;r<x;r++)v=o[l[r]][0],m[0][a.isReversed(e)?x-r-1:r]=v;x=1}return e._lgroupsLength=x,m}},{"../../registry":247,"./helpers":104}],103:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../registry"),i=!0;e.exports=function(t,e,r){if(!e._dragged&&!e._editing){var o,l,s,c,u,f=e._fullLayout.hiddenlabels?e._fullLayout.hiddenlabels.slice():[],d=t.data()[0][0],p=e._fullData,h=d.trace,g=h.legendgroup,y={},v=[],m=[],x=[];if(1===r&&i&&e.data&&e._context.showTips?(n.notifier(n._(e,"Double-click on legend to isolate one trace"),"long"),i=!1):i=!1,a.traceIs(h,"pie")){var b=d.label,_=f.indexOf(b);1===r?-1===_?f.push(b):f.splice(_,1):2===r&&(f=[],e.calcdata[0].forEach(function(t){b!==t.label&&f.push(t.label)}),e._fullLayout.hiddenlabels&&e._fullLayout.hiddenlabels.length===f.length&&-1===_&&(f=[])),a.call("relayout",e,"hiddenlabels",f)}else{var w,k=g&&g.length,M=[];if(k)for(o=0;o<p.length;o++)(w=p[o]).visible&&w.legendgroup===g&&M.push(o);if(1===r){var T;switch(h.visible){case!0:T="legendonly";break;case!1:T=!1;break;case"legendonly":T=!0}if(k)for(o=0;o<p.length;o++)!1!==p[o].visible&&p[o].legendgroup===g&&D(p[o],T);else D(h,T)}else if(2===r){var A,L,C=!0;for(o=0;o<p.length;o++)if(!(p[o]===h)&&!(A=k&&p[o].legendgroup===g)&&!0===p[o].visible&&!a.traceIs(p[o],"notLegendIsolatable")){C=!1;break}for(o=0;o<p.length;o++)if(!1!==p[o].visible&&!a.traceIs(p[o],"notLegendIsolatable"))switch(h.visible){case"legendonly":D(p[o],!0);break;case!0:L=!!C||"legendonly",A=p[o]===h||k&&p[o].legendgroup===g,D(p[o],!!A||L)}}for(o=0;o<m.length;o++)if(s=m[o]){var S=s.constructUpdate(),O=Object.keys(S);for(l=0;l<O.length;l++)c=O[l],(y[c]=y[c]||[])[x[o]]=S[c]}for(u=Object.keys(y),o=0;o<u.length;o++)for(c=u[o],l=0;l<v.length;l++)y[c].hasOwnProperty(l)||(y[c][l]=void 0);a.call("restyle",e,y,v)}}function P(t,e,r){var n=v.indexOf(t),a=y[e];return a||(a=y[e]=[]),-1===v.indexOf(t)&&(v.push(t),n=v.length-1),a[n]=r,n}function D(t,e){var r=t._fullInput;if(a.hasTransform(r,"groupby")){var i=m[r.index];if(!i){var o=a.getTransformIndices(r,"groupby"),l=o[o.length-1];i=n.keyedContainer(r,"transforms["+l+"].styles","target","value.visible"),m[r.index]=i}var s=i.get(t._group);void 0===s&&(s=!0),!1!==s&&i.set(t._group,e),x[r.index]=P(r.index,"visible",!1!==r.visible)}else{var c=!1!==r.visible&&e;P(r.index,"visible",c)}}}},{"../../lib":163,"../../registry":247}],104:[function(t,e,r){"use strict";r.legendGetsTrace=function(t){return t.visible&&void 0!==t.showlegend},r.isGrouped=function(t){return-1!==(t.traceorder||"").indexOf("grouped")},r.isVertical=function(t){return"h"!==t.orientation},r.isReversed=function(t){return-1!==(t.traceorder||"").indexOf("reversed")}},{}],105:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"legend",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),draw:t("./draw"),style:t("./style")}},{"./attributes":98,"./defaults":100,"./draw":101,"./style":106}],106:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../lib"),o=t("../drawing"),l=t("../color"),s=t("../../traces/scatter/subtypes"),c=t("../../traces/pie/style_one");e.exports=function(t,e){t.each(function(t){var e=n.select(this),r=i.ensureSingle(e,"g","layers");r.style("opacity",t[0].trace.opacity),r.selectAll("g.legendfill").data([t]).enter().append("g").classed("legendfill",!0),r.selectAll("g.legendlines").data([t]).enter().append("g").classed("legendlines",!0);var a=r.selectAll("g.legendsymbols").data([t]);a.enter().append("g").classed("legendsymbols",!0),a.selectAll("g.legendpoints").data([t]).enter().append("g").classed("legendpoints",!0)}).each(function(t){var e=t[0].trace,r=e.marker||{},i=r.line||{},o=n.select(this).select("g.legendpoints").selectAll("path.legendbar").data(a.traceIs(e,"bar")?[t]:[]);o.enter().append("path").classed("legendbar",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),o.exit().remove(),o.each(function(t){var e=n.select(this),a=t[0],o=(a.mlw+1||i.width+1)-1;e.style("stroke-width",o+"px").call(l.fill,a.mc||r.color),o&&e.call(l.stroke,a.mlc||i.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendbox").data(a.traceIs(e,"box-violin")&&e.visible?[t]:[]);r.enter().append("path").classed("legendbox",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.each(function(){var t=e.line.width,r=n.select(this);r.style("stroke-width",t+"px").call(l.fill,e.fillcolor),t&&l.stroke(r,e.line.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendpie").data(a.traceIs(e,"pie")&&e.visible?[t]:[]);r.enter().append("path").classed("legendpie",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.size()&&r.call(c,t[0],e)}).each(function(t){var e=t[0].trace,r=e.visible&&e.fill&&"none"!==e.fill,a=s.hasLines(e),i=e.contours;i&&"constraint"===i.type&&(a=i.showlines,r="="!==i._operation);var l=n.select(this).select(".legendfill").selectAll("path").data(r?[t]:[]);l.enter().append("path").classed("js-fill",!0),l.exit().remove(),l.attr("d","M5,0h30v6h-30z").call(o.fillGroupStyle);var c=n.select(this).select(".legendlines").selectAll("path").data(a?[t]:[]);c.enter().append("path").classed("js-line",!0).attr("d","M5,0h30"),c.exit().remove(),c.call(o.lineGroupStyle)}).each(function(t){var r,a,l=t[0],c=l.trace,u=s.hasMarkers(c),f=s.hasText(c),d=s.hasLines(c);function p(t,e,r){var n=i.nestedProperty(c,t).get(),a=Array.isArray(n)&&e?e(n):n;if(r){if(a<r[0])return r[0];if(a>r[1])return r[1]}return a}function h(t){return t[0]}if(u||f||d){var g={},y={};u&&(g.mc=p("marker.color",h),g.mx=p("marker.symbol",h),g.mo=p("marker.opacity",i.mean,[.2,1]),g.ms=p("marker.size",i.mean,[2,16]),g.mlc=p("marker.line.color",h),g.mlw=p("marker.line.width",i.mean,[0,5]),y.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),d&&(y.line={width:p("line.width",h,[0,10])}),f&&(g.tx="Aa",g.tp=p("textposition",h),g.ts=10,g.tc=p("textfont.color",h),g.tf=p("textfont.family",h)),r=[i.minExtend(l,g)],(a=i.minExtend(c,y)).selectedpoints=null}var v=n.select(this).select("g.legendpoints"),m=v.selectAll("path.scatterpts").data(u?r:[]);m.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),m.exit().remove(),m.call(o.pointStyle,a,e),u&&(r[0].mrc=3);var x=v.selectAll("g.pointtext").data(f?r:[]);x.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),x.exit().remove(),x.selectAll("text").call(o.textPointStyle,a,e)}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendcandle").data("candlestick"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendcandle",!0).attr("d",function(t,e){return e?"M-15,0H-8M-8,6V-6H8Z":"M15,0H8M8,-6V6H-8Z"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=e[r?"increasing":"decreasing"],i=a.line.width,o=n.select(this);o.style("stroke-width",i+"px").call(l.fill,a.fillcolor),i&&l.stroke(o,a.line.color)})}).each(function(t){var e=t[0].trace,r=n.select(this).select("g.legendpoints").selectAll("path.legendohlc").data("ohlc"===e.type&&e.visible?[t,t]:[]);r.enter().append("path").classed("legendohlc",!0).attr("d",function(t,e){return e?"M-15,0H0M-8,-6V0":"M15,0H0M8,6V0"}).attr("transform","translate(20,0)").style("stroke-miterlimit",1),r.exit().remove(),r.each(function(t,r){var a=e[r?"increasing":"decreasing"],i=a.line.width,s=n.select(this);s.style("fill","none").call(o.dashLine,a.line.dash,i),i&&l.stroke(s,a.line.color)})})}},{"../../lib":163,"../../registry":247,"../../traces/pie/style_one":312,"../../traces/scatter/subtypes":336,"../color":45,"../drawing":70,d3:10}],107:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../plots/plots"),i=t("../../plots/cartesian/axis_ids"),o=t("../../lib"),l=t("../../../build/ploticon"),s=o._,c=e.exports={};function u(t,e){var r,a,o=e.currentTarget,l=o.getAttribute("data-attr"),s=o.getAttribute("data-val")||!0,c=t._fullLayout,u={},f=i.list(t,null,!0),d="on";if("zoom"===l){var p,h="in"===s?.5:2,g=(1+h)/2,y=(1-h)/2;for(a=0;a<f.length;a++)if(!(r=f[a]).fixedrange)if(p=r._name,"auto"===s)u[p+".autorange"]=!0;else if("reset"===s){if(void 0===r._rangeInitial)u[p+".autorange"]=!0;else{var v=r._rangeInitial.slice();u[p+".range[0]"]=v[0],u[p+".range[1]"]=v[1]}void 0!==r._showSpikeInitial&&(u[p+".showspikes"]=r._showSpikeInitial,"on"!==d||r._showSpikeInitial||(d="off"))}else{var m=[r.r2l(r.range[0]),r.r2l(r.range[1])],x=[g*m[0]+y*m[1],g*m[1]+y*m[0]];u[p+".range[0]"]=r.l2r(x[0]),u[p+".range[1]"]=r.l2r(x[1])}c._cartesianSpikesEnabled=d}else{if("hovermode"!==l||"x"!==s&&"y"!==s){if("hovermode"===l&&"closest"===s){for(a=0;a<f.length;a++)r=f[a],"on"!==d||r.showspikes||(d="off");c._cartesianSpikesEnabled=d}}else s=c._isHoriz?"y":"x",o.setAttribute("data-val",s);u[l]=s}n.call("relayout",t,u)}function f(t,e){for(var r=e.currentTarget,a=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,o=t._fullLayout._subplots.gl3d,l={},s=a.split("."),c=0;c<o.length;c++)l[o[c]+"."+s[1]]=i;var u="pan"===i?i:"zoom";l.dragmode=u,n.call("relayout",t,l)}function d(t,e){for(var r=e.currentTarget.getAttribute("data-attr"),a=t._fullLayout,i=a._subplots.gl3d,l={},s=0;s<i.length;s++){var c=i[s],u=c+".camera",f=a[c]._scene;"resetDefault"===r?l[u]=null:"resetLastSave"===r&&(l[u]=o.extendDeep({},f.cameraInitial))}n.call("relayout",t,l)}function p(t,e){var r=e.currentTarget,a=r._previousVal||!1,i=t.layout,l=t._fullLayout,s=l._subplots.gl3d,c=["xaxis","yaxis","zaxis"],u=["showspikes","spikesides","spikethickness","spikecolor"],f={},d={},p={};if(a)p=o.extendDeep(i,a),r._previousVal=null;else{p={"allaxes.showspikes":!1};for(var h=0;h<s.length;h++){var g=s[h],y=l[g],v=f[g]={};v.hovermode=y.hovermode,p[g+".hovermode"]=!1;for(var m=0;m<3;m++){var x=c[m];d=v[x]={};for(var b=0;b<u.length;b++){var _=u[b];d[_]=y[x][_]}}}r._previousVal=o.extendDeep({},f)}n.call("relayout",t,p)}function h(t,e){for(var r=e.currentTarget,a=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,o=t._fullLayout,l=o._subplots.geo,s=0;s<l.length;s++){var c=l[s],u=o[c];if("zoom"===a){var f=u.projection.scale,d="in"===i?2*f:.5*f;n.call("relayout",t,c+".projection.scale",d)}else"reset"===a&&y(t,"geo")}}function g(t){var e,r=t._fullLayout;e=r._has("cartesian")?r._isHoriz?"y":"x":"closest";var a=!t._fullLayout.hovermode&&e;n.call("relayout",t,"hovermode",a)}function y(t,e){for(var r=t._fullLayout,a=r._subplots[e],i={},o=0;o<a.length;o++)for(var l=a[o],s=r[l]._subplot.viewInitial,c=Object.keys(s),u=0;u<c.length;u++){var f=c[u];i[l+"."+f]=s[f]}n.call("relayout",t,i)}c.toImage={name:"toImage",title:function(t){var e=(t._context.toImageButtonOptions||{}).format||"png";return s(t,"png"===e?"Download plot as a png":"Download plot")},icon:l.camera,click:function(t){var e=t._context.toImageButtonOptions,r={format:e.format||"png"};o.notifier(s(t,"Taking snapshot - this may take a few seconds"),"long"),"svg"!==r.format&&o.isIE()&&(o.notifier(s(t,"IE only supports svg. Changing format to svg."),"long"),r.format="svg"),["filename","width","height","scale"].forEach(function(t){e[t]&&(r[t]=e[t])}),n.call("downloadImage",t,r).then(function(e){o.notifier(s(t,"Snapshot succeeded")+" - "+e,"long")}).catch(function(){o.notifier(s(t,"Sorry, there was a problem downloading your snapshot!"),"long")})}},c.sendDataToCloud={name:"sendDataToCloud",title:function(t){return s(t,"Edit in Chart Studio")},icon:l.disk,click:function(t){a.sendDataToCloud(t)}},c.zoom2d={name:"zoom2d",title:function(t){return s(t,"Zoom")},attr:"dragmode",val:"zoom",icon:l.zoombox,click:u},c.pan2d={name:"pan2d",title:function(t){return s(t,"Pan")},attr:"dragmode",val:"pan",icon:l.pan,click:u},c.select2d={name:"select2d",title:function(t){return s(t,"Box Select")},attr:"dragmode",val:"select",icon:l.selectbox,click:u},c.lasso2d={name:"lasso2d",title:function(t){return s(t,"Lasso Select")},attr:"dragmode",val:"lasso",icon:l.lasso,click:u},c.zoomIn2d={name:"zoomIn2d",title:function(t){return s(t,"Zoom in")},attr:"zoom",val:"in",icon:l.zoom_plus,click:u},c.zoomOut2d={name:"zoomOut2d",title:function(t){return s(t,"Zoom out")},attr:"zoom",val:"out",icon:l.zoom_minus,click:u},c.autoScale2d={name:"autoScale2d",title:function(t){return s(t,"Autoscale")},attr:"zoom",val:"auto",icon:l.autoscale,click:u},c.resetScale2d={name:"resetScale2d",title:function(t){return s(t,"Reset axes")},attr:"zoom",val:"reset",icon:l.home,click:u},c.hoverClosestCartesian={name:"hoverClosestCartesian",title:function(t){return s(t,"Show closest data on hover")},attr:"hovermode",val:"closest",icon:l.tooltip_basic,gravity:"ne",click:u},c.hoverCompareCartesian={name:"hoverCompareCartesian",title:function(t){return s(t,"Compare data on hover")},attr:"hovermode",val:function(t){return t._fullLayout._isHoriz?"y":"x"},icon:l.tooltip_compare,gravity:"ne",click:u},c.zoom3d={name:"zoom3d",title:function(t){return s(t,"Zoom")},attr:"scene.dragmode",val:"zoom",icon:l.zoombox,click:f},c.pan3d={name:"pan3d",title:function(t){return s(t,"Pan")},attr:"scene.dragmode",val:"pan",icon:l.pan,click:f},c.orbitRotation={name:"orbitRotation",title:function(t){return s(t,"Orbital rotation")},attr:"scene.dragmode",val:"orbit",icon:l["3d_rotate"],click:f},c.tableRotation={name:"tableRotation",title:function(t){return s(t,"Turntable rotation")},attr:"scene.dragmode",val:"turntable",icon:l["z-axis"],click:f},c.resetCameraDefault3d={name:"resetCameraDefault3d",title:function(t){return s(t,"Reset camera to default")},attr:"resetDefault",icon:l.home,click:d},c.resetCameraLastSave3d={name:"resetCameraLastSave3d",title:function(t){return s(t,"Reset camera to last save")},attr:"resetLastSave",icon:l.movie,click:d},c.hoverClosest3d={name:"hoverClosest3d",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:l.tooltip_basic,gravity:"ne",click:p},c.zoomInGeo={name:"zoomInGeo",title:function(t){return s(t,"Zoom in")},attr:"zoom",val:"in",icon:l.zoom_plus,click:h},c.zoomOutGeo={name:"zoomOutGeo",title:function(t){return s(t,"Zoom out")},attr:"zoom",val:"out",icon:l.zoom_minus,click:h},c.resetGeo={name:"resetGeo",title:function(t){return s(t,"Reset")},attr:"reset",val:null,icon:l.autoscale,click:h},c.hoverClosestGeo={name:"hoverClosestGeo",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:l.tooltip_basic,gravity:"ne",click:g},c.hoverClosestGl2d={name:"hoverClosestGl2d",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:l.tooltip_basic,gravity:"ne",click:g},c.hoverClosestPie={name:"hoverClosestPie",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:"closest",icon:l.tooltip_basic,gravity:"ne",click:g},c.toggleHover={name:"toggleHover",title:function(t){return s(t,"Toggle show closest data on hover")},attr:"hovermode",val:null,toggle:!0,icon:l.tooltip_basic,gravity:"ne",click:function(t,e){g(t),p(t,e)}},c.resetViews={name:"resetViews",title:function(t){return s(t,"Reset views")},icon:l.home,click:function(t,e){var r=e.currentTarget;r.setAttribute("data-attr","zoom"),r.setAttribute("data-val","reset"),u(t,e),r.setAttribute("data-attr","resetLastSave"),d(t,e),y(t,"geo"),y(t,"mapbox")}},c.toggleSpikelines={name:"toggleSpikelines",title:function(t){return s(t,"Toggle Spike Lines")},icon:l.spikeline,attr:"_cartesianSpikesEnabled",val:"on",click:function(t){var e=t._fullLayout;e._cartesianSpikesEnabled="on"===e._cartesianSpikesEnabled?"off":"on";var r=function(t){for(var e,r,n=t._fullLayout,a=i.list(t,null,!0),o={},l=0;l<a.length;l++)e=a[l],r=e._name,o[r+".showspikes"]="on"===n._cartesianSpikesEnabled||e._showSpikeInitial;return o}(t);n.call("relayout",t,r)}},c.resetViewMapbox={name:"resetViewMapbox",title:function(t){return s(t,"Reset view")},attr:"reset",icon:l.home,click:function(t){y(t,"mapbox")}}},{"../../../build/ploticon":2,"../../lib":163,"../../plots/cartesian/axis_ids":210,"../../plots/plots":239,"../../registry":247}],108:[function(t,e,r){"use strict";r.manage=t("./manage")},{"./manage":109}],109:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axis_ids"),a=t("../../traces/scatter/subtypes"),i=t("../../registry"),o=t("./modebar"),l=t("./buttons");e.exports=function(t){var e=t._fullLayout,r=t._context,s=e._modeBar;if(r.displayModeBar){if(!Array.isArray(r.modeBarButtonsToRemove))throw new Error(["*modeBarButtonsToRemove* configuration options","must be an array."].join(" "));if(!Array.isArray(r.modeBarButtonsToAdd))throw new Error(["*modeBarButtonsToAdd* configuration options","must be an array."].join(" "));var c,u=r.modeBarButtons;c=Array.isArray(u)&&u.length?function(t){for(var e=0;e<t.length;e++)for(var r=t[e],n=0;n<r.length;n++){var a=r[n];if("string"==typeof a){if(void 0===l[a])throw new Error(["*modeBarButtons* configuration options","invalid button name"].join(" "));t[e][n]=l[a]}}return t}(u):function(t,e,r){var o=t._fullLayout,s=t._fullData,c=o._has("cartesian"),u=o._has("gl3d"),f=o._has("geo"),d=o._has("pie"),p=o._has("gl2d"),h=o._has("ternary"),g=o._has("mapbox"),y=o._has("polar"),v=function(t){for(var e=n.list({_fullLayout:t},null,!0),r=0;r<e.length;r++)if(!e[r].fixedrange)return!1;return!0}(o),m=[];function x(t){if(t.length){for(var r=[],n=0;n<t.length;n++){var a=t[n];-1===e.indexOf(a)&&r.push(l[a])}m.push(r)}}x(["toImage","sendDataToCloud"]);var b=[],_=[],w=[],k=[];(c||p||d||h)+f+u+g+y>1?(_=["toggleHover"],w=["resetViews"]):f?(b=["zoomInGeo","zoomOutGeo"],_=["hoverClosestGeo"],w=["resetGeo"]):u?(_=["hoverClosest3d"],w=["resetCameraDefault3d","resetCameraLastSave3d"]):g?(_=["toggleHover"],w=["resetViewMapbox"]):_=p?["hoverClosestGl2d"]:d?["hoverClosestPie"]:["toggleHover"];c&&(_=["toggleSpikelines","hoverClosestCartesian","hoverCompareCartesian"]);!c&&!p||v||(b=["zoomIn2d","zoomOut2d","autoScale2d"],"resetViews"!==w[0]&&(w=["resetScale2d"]));u?k=["zoom3d","pan3d","orbitRotation","tableRotation"]:(c||p)&&!v||h?k=["zoom2d","pan2d"]:g||f?k=["pan2d"]:y&&(k=["zoom2d"]);(function(t){for(var e=!1,r=0;r<t.length&&!e;r++){var n=t[r];n._module&&n._module.selectPoints&&(i.traceIs(n,"scatter-like")?(a.hasMarkers(n)||a.hasText(n))&&(e=!0):i.traceIs(n,"box-violin")&&"all"!==n.boxpoints&&"all"!==n.points||(e=!0))}return e})(s)&&k.push("select2d","lasso2d");return x(k),x(b.concat(w)),x(_),function(t,e){if(e.length)if(Array.isArray(e[0]))for(var r=0;r<e.length;r++)t.push(e[r]);else t.push(e);return t}(m,r)}(t,r.modeBarButtonsToRemove,r.modeBarButtonsToAdd),s?s.update(t,c):e._modeBar=o(t,c)}else s&&(s.destroy(),delete e._modeBar)}},{"../../plots/cartesian/axis_ids":210,"../../registry":247,"../../traces/scatter/subtypes":336,"./buttons":107,"./modebar":110}],110:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../../lib"),o=t("../../../build/ploticon");function l(t){this.container=t.container,this.element=document.createElement("div"),this.update(t.graphInfo,t.buttons),this.container.appendChild(this.element)}var s=l.prototype;s.update=function(t,e){this.graphInfo=t;var r=this.graphInfo._context;"hover"===r.displayModeBar?this.element.className="modebar modebar--hover":this.element.className="modebar";var n=!this.hasButtons(e),a=this.hasLogo!==r.displaylogo,i=this.locale!==r.locale;this.locale=r.locale,(n||a||i)&&(this.removeAllButtons(),this.updateButtons(e),r.displaylogo&&(this.element.appendChild(this.getLogo()),this.hasLogo=!0)),this.updateActiveButton()},s.updateButtons=function(t){var e=this;this.buttons=t,this.buttonElements=[],this.buttonsNames=[],this.buttons.forEach(function(t){var r=e.createGroup();t.forEach(function(t){var n=t.name;if(!n)throw new Error("must provide button 'name' in button config");if(-1!==e.buttonsNames.indexOf(n))throw new Error("button name '"+n+"' is taken");e.buttonsNames.push(n);var a=e.createButton(t);e.buttonElements.push(a),r.appendChild(a)}),e.element.appendChild(r)})},s.createGroup=function(){var t=document.createElement("div");return t.className="modebar-group",t},s.createButton=function(t){var e=this,r=document.createElement("a");r.setAttribute("rel","tooltip"),r.className="modebar-btn";var a=t.title;void 0===a?a=t.name:"function"==typeof a&&(a=a(this.graphInfo)),(a||0===a)&&r.setAttribute("data-title",a),void 0!==t.attr&&r.setAttribute("data-attr",t.attr);var i=t.val;if(void 0!==i&&("function"==typeof i&&(i=i(this.graphInfo)),r.setAttribute("data-val",i)),"function"!=typeof t.click)throw new Error("must provide button 'click' function in button config");r.addEventListener("click",function(r){t.click(e.graphInfo,r),e.updateActiveButton(r.currentTarget)}),r.setAttribute("data-toggle",t.toggle||!1),t.toggle&&n.select(r).classed("active",!0);var l=t.icon;return"function"==typeof l?r.appendChild(l()):r.appendChild(this.createIcon(l||o.question)),r.setAttribute("data-gravity",t.gravity||"n"),r},s.createIcon=function(t){var e=a(t.height)?Number(t.height):t.ascent-t.descent,r="http://www.w3.org/2000/svg",n=document.createElementNS(r,"svg"),i=document.createElementNS(r,"path");return n.setAttribute("height","1em"),n.setAttribute("width",t.width/e+"em"),n.setAttribute("viewBox",[0,0,t.width,e].join(" ")),i.setAttribute("d",t.path),t.transform?i.setAttribute("transform",t.transform):void 0!==t.ascent&&i.setAttribute("transform","matrix(1 0 0 -1 0 "+t.ascent+")"),n.appendChild(i),n},s.updateActiveButton=function(t){var e=this.graphInfo._fullLayout,r=void 0!==t?t.getAttribute("data-attr"):null;this.buttonElements.forEach(function(t){var a=t.getAttribute("data-val")||!0,o=t.getAttribute("data-attr"),l="true"===t.getAttribute("data-toggle"),s=n.select(t);if(l)o===r&&s.classed("active",!s.classed("active"));else{var c=null===o?o:i.nestedProperty(e,o).get();s.classed("active",c===a)}})},s.hasButtons=function(t){var e=this.buttons;if(!e)return!1;if(t.length!==e.length)return!1;for(var r=0;r<t.length;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n<t[r].length;n++)if(t[r][n].name!==e[r][n].name)return!1}return!0},s.getLogo=function(){var t=this.createGroup(),e=document.createElement("a");return e.href="https://plot.ly/",e.target="_blank",e.setAttribute("data-title",i._(this.graphInfo,"Produced with Plotly")),e.className="modebar-btn plotlyjsicon modebar-btn--logo",e.appendChild(this.createIcon(o.plotlylogo)),t.appendChild(e),t},s.removeAllButtons=function(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);this.hasLogo=!1},s.destroy=function(){i.removeElement(this.container.querySelector(".modebar"))},e.exports=function(t,e){var r=t._fullLayout,a=new l({graphInfo:t,container:r._paperdiv.node(),buttons:e});return r._privateplot&&n.select(a.element).append("span").classed("badge-private float--left",!0).text("PRIVATE"),a}},{"../../../build/ploticon":2,"../../lib":163,d3:10,"fast-isnumeric":13}],111:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),a=t("../color/attributes"),i=(0,t("../../plot_api/plot_template").templatedArray)("button",{visible:{valType:"boolean",dflt:!0,editType:"plot"},step:{valType:"enumerated",values:["month","year","day","hour","minute","second","all"],dflt:"month",editType:"plot"},stepmode:{valType:"enumerated",values:["backward","todate"],dflt:"backward",editType:"plot"},count:{valType:"number",min:0,dflt:1,editType:"plot"},label:{valType:"string",editType:"plot"},editType:"plot"});e.exports={visible:{valType:"boolean",editType:"plot"},buttons:i,x:{valType:"number",min:-2,max:3,editType:"plot"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left",editType:"plot"},y:{valType:"number",min:-2,max:3,editType:"plot"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"bottom",editType:"plot"},font:n({editType:"plot"}),bgcolor:{valType:"color",dflt:a.lightLine,editType:"plot"},activecolor:{valType:"color",editType:"plot"},bordercolor:{valType:"color",dflt:a.defaultLine,editType:"plot"},borderwidth:{valType:"number",min:0,dflt:0,editType:"plot"},editType:"plot"}},{"../../plot_api/plot_template":197,"../../plots/font_attributes":233,"../color/attributes":44}],112:[function(t,e,r){"use strict";e.exports={yPad:.02,minButtonWidth:30,rx:3,ry:3,lightAmount:25,darkAmount:10}},{}],113:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../color"),i=t("../../plot_api/plot_template"),o=t("../../plots/array_container_defaults"),l=t("./attributes"),s=t("./constants");function c(t,e,r,a){var i=a.calendar;function o(r,a){return n.coerce(t,e,l.buttons,r,a)}if(o("visible")){var s=o("step");"all"!==s&&(!i||"gregorian"===i||"month"!==s&&"year"!==s?o("stepmode"):e.stepmode="backward",o("count")),o("label")}}e.exports=function(t,e,r,u,f){var d=t.rangeselector||{},p=i.newContainer(e,"rangeselector");function h(t,e){return n.coerce(d,p,l,t,e)}if(h("visible",o(d,p,{name:"buttons",handleItemDefaults:c,calendar:f}).length>0)){var g=function(t,e,r){for(var n=r.filter(function(r){return e[r].anchor===t._id}),a=0,i=0;i<n.length;i++){var o=e[n[i]].domain;o&&(a=Math.max(o[1],a))}return[t.domain[0],a+s.yPad]}(e,r,u);h("x",g[0]),h("y",g[1]),n.noneOrAll(t,e,["x","y"]),h("xanchor"),h("yanchor"),n.coerceFont(h,"font",r.font);var y=h("bgcolor");h("activecolor",a.contrast(y,s.lightAmount,s.darkAmount)),h("bordercolor"),h("borderwidth")}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../plots/array_container_defaults":203,"../color":45,"./attributes":111,"./constants":112}],114:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../plots/plots"),o=t("../color"),l=t("../drawing"),s=t("../../lib"),c=t("../../lib/svg_text_utils"),u=t("../../plots/cartesian/axis_ids"),f=t("../legend/anchor_utils"),d=t("../../constants/alignment"),p=d.LINE_SPACING,h=d.FROM_TL,g=d.FROM_BR,y=t("./constants"),v=t("./get_update_object");function m(t){return t._id}function x(t,e,r){var n=s.ensureSingle(t,"rect","selector-rect",function(t){t.attr("shape-rendering","crispEdges")});n.attr({rx:y.rx,ry:y.ry}),n.call(o.stroke,e.bordercolor).call(o.fill,function(t,e){return e._isActive||e._isHovered?t.activecolor:t.bgcolor}(e,r)).style("stroke-width",e.borderwidth+"px")}function b(t,e,r,n){var a;s.ensureSingle(t,"text","selector-text",function(t){t.classed("user-select-none",!0).attr("text-anchor","middle")}).call(l.font,e.font).text((a=r,a.label?a.label:"all"===a.step?"all":a.count+a.step.charAt(0))).call(function(t){c.convertToTspans(t,n)})}e.exports=function(t){var e=t._fullLayout._infolayer.selectAll(".rangeselector").data(function(t){for(var e=u.list(t,"x",!0),r=[],n=0;n<e.length;n++){var a=e[n];a.rangeselector&&a.rangeselector.visible&&r.push(a)}return r}(t),m);e.enter().append("g").classed("rangeselector",!0),e.exit().remove(),e.style({cursor:"pointer","pointer-events":"all"}),e.each(function(e){var r=n.select(this),o=e,u=o.rangeselector,d=r.selectAll("g.button").data(s.filterVisible(u.buttons));d.enter().append("g").classed("button",!0),d.exit().remove(),d.each(function(e){var r=n.select(this),i=v(o,e);e._isActive=function(t,e,r){if("all"===e.step)return!0===t.autorange;var n=Object.keys(r);return t.range[0]===r[n[0]]&&t.range[1]===r[n[1]]}(o,e,i),r.call(x,u,e),r.call(b,u,e,t),r.on("click",function(){t._dragged||a.call("relayout",t,i)}),r.on("mouseover",function(){e._isHovered=!0,r.call(x,u,e)}),r.on("mouseout",function(){e._isHovered=!1,r.call(x,u,e)})}),function(t,e,r,a,o){var s=0,u=0,d=r.borderwidth;e.each(function(){var t=n.select(this),e=t.select(".selector-text"),a=r.font.size*p,i=Math.max(a*c.lineCount(e),16)+3;u=Math.max(u,i)}),e.each(function(){var t=n.select(this),e=t.select(".selector-rect"),a=t.select(".selector-text"),i=a.node()&&l.bBox(a.node()).width,o=r.font.size*p,f=c.lineCount(a),h=Math.max(i+10,y.minButtonWidth);t.attr("transform","translate("+(d+s)+","+d+")"),e.attr({x:0,y:0,width:h,height:u}),c.positionText(a,h/2,u/2-(f-1)*o/2+3),s+=h+5});var v=t._fullLayout._size,m=v.l+v.w*r.x,x=v.t+v.h*(1-r.y),b="left";f.isRightAnchor(r)&&(m-=s,b="right");f.isCenterAnchor(r)&&(m-=s/2,b="center");var _="top";f.isBottomAnchor(r)&&(x-=u,_="bottom");f.isMiddleAnchor(r)&&(x-=u/2,_="middle");s=Math.ceil(s),u=Math.ceil(u),m=Math.round(m),x=Math.round(x),i.autoMargin(t,a+"-range-selector",{x:r.x,y:r.y,l:s*h[b],r:s*g[b],b:u*g[_],t:u*h[_]}),o.attr("transform","translate("+m+","+x+")")}(t,d,u,o._name,r)})}},{"../../constants/alignment":143,"../../lib":163,"../../lib/svg_text_utils":184,"../../plots/cartesian/axis_ids":210,"../../plots/plots":239,"../../registry":247,"../color":45,"../drawing":70,"../legend/anchor_utils":97,"./constants":112,"./get_update_object":115,d3:10}],115:[function(t,e,r){"use strict";var n=t("d3");e.exports=function(t,e){var r=t._name,a={};if("all"===e.step)a[r+".autorange"]=!0;else{var i=function(t,e){var r,a=t.range,i=new Date(t.r2l(a[1])),o=e.step,l=e.count;switch(e.stepmode){case"backward":r=t.l2r(+n.time[o].utc.offset(i,-l));break;case"todate":var s=n.time[o].utc.offset(i,-l);r=t.l2r(+n.time[o].utc.ceil(s))}var c=a[1];return[r,c]}(t,e);a[r+".range[0]"]=i[0],a[r+".range[1]"]=i[1]}return a}},{d3:10}],116:[function(t,e,r){"use strict";e.exports={moduleType:"component",name:"rangeselector",schema:{subplots:{xaxis:{rangeselector:t("./attributes")}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),draw:t("./draw")}},{"./attributes":111,"./defaults":113,"./draw":114}],117:[function(t,e,r){"use strict";var n=t("../color/attributes");e.exports={bgcolor:{valType:"color",dflt:n.background,editType:"plot"},bordercolor:{valType:"color",dflt:n.defaultLine,editType:"plot"},borderwidth:{valType:"integer",dflt:0,min:0,editType:"plot"},autorange:{valType:"boolean",dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},range:{valType:"info_array",items:[{valType:"any",editType:"calc",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"calc",impliedEdits:{"^autorange":!1}}],editType:"calc",impliedEdits:{autorange:!1}},thickness:{valType:"number",dflt:.15,min:0,max:1,editType:"plot"},visible:{valType:"boolean",dflt:!0,editType:"calc"},editType:"calc"}},{"../color/attributes":44}],118:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axis_ids").list,a=t("../../plots/cartesian/autorange").getAutoRange,i=t("./constants");e.exports=function(t){for(var e=n(t,"x",!0),r=0;r<e.length;r++){var o=e[r],l=o[i.name];l&&l.visible&&l.autorange&&o._min.length&&o._max.length&&(l._input.autorange=!0,l._input.range=l.range=a(o))}}},{"../../plots/cartesian/autorange":206,"../../plots/cartesian/axis_ids":210,"./constants":119}],119:[function(t,e,r){"use strict";e.exports={name:"rangeslider",containerClassName:"rangeslider-container",bgClassName:"rangeslider-bg",rangePlotClassName:"rangeslider-rangeplot",maskMinClassName:"rangeslider-mask-min",maskMaxClassName:"rangeslider-mask-max",slideBoxClassName:"rangeslider-slidebox",grabberMinClassName:"rangeslider-grabber-min",grabAreaMinClassName:"rangeslider-grabarea-min",handleMinClassName:"rangeslider-handle-min",grabberMaxClassName:"rangeslider-grabber-max",grabAreaMaxClassName:"rangeslider-grabarea-max",handleMaxClassName:"rangeslider-handle-max",maskMinOppAxisClassName:"rangeslider-mask-min-opp-axis",maskMaxOppAxisClassName:"rangeslider-mask-max-opp-axis",maskColor:"rgba(0,0,0,0.4)",maskOppAxisColor:"rgba(0,0,0,0.2)",slideBoxFill:"transparent",slideBoxCursor:"ew-resize",grabAreaFill:"transparent",grabAreaCursor:"col-resize",grabAreaWidth:10,handleWidth:4,handleRadius:1,handleStrokeWidth:1,extraPad:15}},{}],120:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plot_api/plot_template"),i=t("../../plots/cartesian/axis_ids"),o=t("./attributes"),l=t("./oppaxis_attributes");e.exports=function(t,e,r){var s=t[r],c=e[r];if(s.rangeslider||e._requestRangeslider[c._id]){n.isPlainObject(s.rangeslider)||(s.rangeslider={});var u,f,d=s.rangeslider,p=a.newContainer(c,"rangeslider");if(w("visible")){w("bgcolor",e.plot_bgcolor),w("bordercolor"),w("borderwidth"),w("thickness"),c._rangesliderAutorange=w("autorange",!c.isValidRange(d.range)),w("range");var h=e._subplots;if(h)for(var g=h.cartesian.filter(function(t){return t.substr(0,t.indexOf("y"))===i.name2id(r)}).map(function(t){return t.substr(t.indexOf("y"),t.length)}),y=n.simpleMap(g,i.id2name),v=0;v<y.length;v++){var m=y[v];u=d[m]||{},f=a.newContainer(p,m,"yaxis");var x,b=e[m];u.range&&b.isValidRange(u.range)&&(x="fixed");var _=k("rangemode",x);"match"!==_&&k("range",b.range.slice()),b._rangesliderAutorange="auto"===_}p._input=d}}function w(t,e){return n.coerce(d,p,o,t,e)}function k(t,e){return n.coerce(u,f,l,t,e)}}},{"../../lib":163,"../../plot_api/plot_template":197,"../../plots/cartesian/axis_ids":210,"./attributes":117,"./oppaxis_attributes":123}],121:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../plots/plots"),o=t("../../lib"),l=t("../drawing"),s=t("../color"),c=t("../titles"),u=t("../../plots/cartesian"),f=t("../../plots/cartesian/axes"),d=t("../dragelement"),p=t("../../lib/setcursor"),h=t("./constants");function g(t,e,r,n){var a=o.ensureSingle(t,"rect",h.bgClassName,function(t){t.attr({x:0,y:0,"shape-rendering":"crispEdges"})}),i=n.borderwidth%2==0?n.borderwidth:n.borderwidth-1,s=-n._offsetShift,c=l.crispRound(e,n.borderwidth);a.attr({width:n._width+i,height:n._height+i,transform:"translate("+s+","+s+")",fill:n.bgcolor,stroke:n.bordercolor,"stroke-width":c})}function y(t,e,r,n){var a=e._fullLayout;o.ensureSingleById(a._topdefs,"clipPath",n._clipId,function(t){t.append("rect").attr({x:0,y:0})}).select("rect").attr({width:n._width,height:n._height})}function v(t,e,r,a){var s,c=f.getSubplots(e,r),d=e.calcdata,p=t.selectAll("g."+h.rangePlotClassName).data(c,o.identity);p.enter().append("g").attr("class",function(t){return h.rangePlotClassName+" "+t}).call(l.setClipUrl,a._clipId),p.order(),p.exit().remove(),p.each(function(t,o){var l=n.select(this),c=0===o,p=f.getFromId(e,t,"y"),h=p._name,g=a[h],y={data:[],layout:{xaxis:{type:r.type,domain:[0,1],range:a.range.slice(),calendar:r.calendar},width:a._width,height:a._height,margin:{t:0,b:0,l:0,r:0}},_context:e._context};y.layout[h]={type:p.type,domain:[0,1],range:"match"!==g.rangemode?g.range.slice():p.range.slice(),calendar:p.calendar},i.supplyDefaults(y);var v={id:t,plotgroup:l,xaxis:y._fullLayout.xaxis,yaxis:y._fullLayout[h],isRangePlot:!0};c?s=v:(v.mainplot="xy",v.mainplotinfo=s),u.rangePlot(e,v,function(t,e){for(var r=[],n=0;n<t.length;n++){var a=t[n],i=a[0].trace;i.xaxis+i.yaxis===e&&r.push(a)}return r}(d,t))})}function m(t,e,r,n,a){(o.ensureSingle(t,"rect",h.maskMinClassName,function(t){t.attr({x:0,y:0,"shape-rendering":"crispEdges"})}).attr("height",n._height).call(s.fill,h.maskColor),o.ensureSingle(t,"rect",h.maskMaxClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("height",n._height).call(s.fill,h.maskColor),"match"!==a.rangemode)&&(o.ensureSingle(t,"rect",h.maskMinOppAxisClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("width",n._width).call(s.fill,h.maskOppAxisColor),o.ensureSingle(t,"rect",h.maskMaxOppAxisClassName,function(t){t.attr({y:0,"shape-rendering":"crispEdges"})}).attr("width",n._width).style("border-top",h.maskOppBorder).call(s.fill,h.maskOppAxisColor))}function x(t,e,r,n){e._context.staticPlot||o.ensureSingle(t,"rect",h.slideBoxClassName,function(t){t.attr({y:0,cursor:h.slideBoxCursor,"shape-rendering":"crispEdges"})}).attr({height:n._height,fill:h.slideBoxFill})}function b(t,e,r,n){var a=o.ensureSingle(t,"g",h.grabberMinClassName),i=o.ensureSingle(t,"g",h.grabberMaxClassName),l={x:0,width:h.handleWidth,rx:h.handleRadius,fill:s.background,stroke:s.defaultLine,"stroke-width":h.handleStrokeWidth,"shape-rendering":"crispEdges"},c={y:Math.round(n._height/4),height:Math.round(n._height/2)};if(o.ensureSingle(a,"rect",h.handleMinClassName,function(t){t.attr(l)}).attr(c),o.ensureSingle(i,"rect",h.handleMaxClassName,function(t){t.attr(l)}).attr(c),!e._context.staticPlot){var u={width:h.grabAreaWidth,x:0,y:0,fill:h.grabAreaFill,cursor:h.grabAreaCursor};o.ensureSingle(a,"rect",h.grabAreaMinClassName,function(t){t.attr(u)}).attr("height",n._height),o.ensureSingle(i,"rect",h.grabAreaMaxClassName,function(t){t.attr(u)}).attr("height",n._height)}}e.exports=function(t){var e=t._fullLayout,r=function(t){var e=f.list({_fullLayout:t},"x",!0),r=h.name,n=[];if(t._has("gl2d"))return n;for(var a=0;a<e.length;a++){var i=e[a];i[r]&&i[r].visible&&n.push(i)}return n}(e);var l=e._infolayer.selectAll("g."+h.containerClassName).data(r,function(t){return t._name});l.enter().append("g").classed(h.containerClassName,!0).attr("pointer-events","all"),l.exit().each(function(t){var r=t[h.name];e._topdefs.select("#"+r._clipId).remove()}).remove(),0!==r.length&&l.each(function(r){var l=n.select(this),s=r[h.name],u=e[f.id2name(r.anchor)],_=s[f.id2name(r.anchor)];if(s.range){var w=s.range,k=r.range;w[0]=r.l2r(Math.min(r.r2l(w[0]),r.r2l(k[0]))),w[1]=r.l2r(Math.max(r.r2l(w[1]),r.r2l(k[1]))),s._input.range=w.slice()}r.cleanRange("rangeslider.range");for(var M=e.margin,T=e._size,A=r.domain,L=(r._boundingBox||{}).height||0,C=1/0,S=f.getSubplots(t,r),O=0;O<S.length;O++){var P=f.getFromId(t,S[O].substr(S[O].indexOf("y")));C=Math.min(C,P.domain[0])}s._id=h.name+r._id,s._clipId=s._id+"-"+e._uid,s._width=T.w*(A[1]-A[0]),s._height=(e.height-M.b-M.t)*s.thickness,s._offsetShift=Math.floor(s.borderwidth/2);var D=Math.round(M.l+T.w*A[0]),z=Math.round(T.t+T.h*(1-C)+L+s._offsetShift+h.extraPad);l.attr("transform","translate("+D+","+z+")");var E=r.r2l(s.range[0]),I=r.r2l(s.range[1]),N=I-E;if(s.p2d=function(t){return t/s._width*N+E},s.d2p=function(t){return(t-E)/N*s._width},s._rl=[E,I],"match"!==_.rangemode){var R=u.r2l(_.range[0]),F=u.r2l(_.range[1])-R;s.d2pOppAxis=function(t){return(t-R)/F*s._height}}l.call(g,t,r,s).call(y,t,r,s).call(v,t,r,s).call(m,t,r,s,_).call(x,t,r,s).call(b,t,r,s),function(t,e,r,i){var l=t.select("rect."+h.slideBoxClassName).node(),s=t.select("rect."+h.grabAreaMinClassName).node(),c=t.select("rect."+h.grabAreaMaxClassName).node();t.on("mousedown",function(){var u=n.event,f=u.target,h=u.clientX,g=h-t.node().getBoundingClientRect().left,y=i.d2p(r._rl[0]),v=i.d2p(r._rl[1]),m=d.coverSlip();function x(t){var u,d,x,b=+t.clientX-h;switch(f){case l:x="ew-resize",u=y+b,d=v+b;break;case s:x="col-resize",u=y+b,d=v;break;case c:x="col-resize",u=y,d=v+b;break;default:x="ew-resize",u=g,d=g+b}if(d<u){var _=d;d=u,u=_}i._pixelMin=u,i._pixelMax=d,p(n.select(m),x),function(t,e,r,n){function i(t){return r.l2r(o.constrain(t,n._rl[0],n._rl[1]))}var l=i(n.p2d(n._pixelMin)),s=i(n.p2d(n._pixelMax));window.requestAnimationFrame(function(){a.call("relayout",e,r._name+".range",[l,s])})}(0,e,r,i)}m.addEventListener("mousemove",x),m.addEventListener("mouseup",function t(){m.removeEventListener("mousemove",x);m.removeEventListener("mouseup",t);o.removeElement(m)})})}(l,t,r,s),function(t,e,r,n,a,i){var l=h.handleWidth/2;function s(t){return o.constrain(t,0,n._width)}function c(t){return o.constrain(t,0,n._height)}function u(t){return o.constrain(t,-l,n._width+l)}var f=s(n.d2p(r._rl[0])),d=s(n.d2p(r._rl[1]));if(t.select("rect."+h.slideBoxClassName).attr("x",f).attr("width",d-f),t.select("rect."+h.maskMinClassName).attr("width",f),t.select("rect."+h.maskMaxClassName).attr("x",d).attr("width",n._width-d),"match"!==i.rangemode){var p=n._height-c(n.d2pOppAxis(a._rl[1])),g=n._height-c(n.d2pOppAxis(a._rl[0]));t.select("rect."+h.maskMinOppAxisClassName).attr("x",f).attr("height",p).attr("width",d-f),t.select("rect."+h.maskMaxOppAxisClassName).attr("x",f).attr("y",g).attr("height",n._height-g).attr("width",d-f),t.select("rect."+h.slideBoxClassName).attr("y",p).attr("height",g-p)}var y=Math.round(u(f-l))-.5,v=Math.round(u(d-l))+.5;t.select("g."+h.grabberMinClassName).attr("transform","translate("+y+",0.5)"),t.select("g."+h.grabberMaxClassName).attr("transform","translate("+v+",0.5)")}(l,0,r,s,u,_),"bottom"===r.side&&c.draw(t,r._id+"title",{propContainer:r,propName:r._name+".title",placeholder:e._dfltTitle.x,attributes:{x:r._offset+r._length/2,y:z+s._height+s._offsetShift+10+1.5*r.titlefont.size,"text-anchor":"middle"}}),i.autoMargin(t,s._id,{x:A[0],y:C,l:0,r:0,t:0,b:s._height+M.b+L,pad:h.extraPad+2*s._offsetShift})})}},{"../../lib":163,"../../lib/setcursor":182,"../../plots/cartesian":218,"../../plots/cartesian/axes":207,"../../plots/plots":239,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"../titles":136,"./constants":119,d3:10}],122:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./attributes"),i=t("./oppaxis_attributes");e.exports={moduleType:"component",name:"rangeslider",schema:{subplots:{xaxis:{rangeslider:n.extendFlat({},a,{yaxis:i})}}},layoutAttributes:t("./attributes"),handleDefaults:t("./defaults"),calcAutorange:t("./calc_autorange"),draw:t("./draw")}},{"../../lib":163,"./attributes":117,"./calc_autorange":118,"./defaults":120,"./draw":121,"./oppaxis_attributes":123}],123:[function(t,e,r){"use strict";e.exports={_isSubplotObj:!0,rangemode:{valType:"enumerated",values:["auto","fixed","match"],dflt:"match",editType:"calc"},range:{valType:"info_array",items:[{valType:"any",editType:"plot"},{valType:"any",editType:"plot"}],editType:"plot"},editType:"calc"}},{}],124:[function(t,e,r){"use strict";var n=t("../annotations/attributes"),a=t("../../traces/scatter/attributes").line,i=t("../drawing/attributes").dash,o=t("../../lib/extend").extendFlat,l=t("../../plot_api/plot_template").templatedArray;e.exports=l("shape",{visible:{valType:"boolean",dflt:!0,editType:"calcIfAutorange+arraydraw"},type:{valType:"enumerated",values:["circle","rect","path","line"],editType:"calcIfAutorange+arraydraw"},layer:{valType:"enumerated",values:["below","above"],dflt:"above",editType:"arraydraw"},xref:o({},n.xref,{}),xsizemode:{valType:"enumerated",values:["scaled","pixel"],dflt:"scaled",editType:"calcIfAutorange+arraydraw"},xanchor:{valType:"any",editType:"calcIfAutorange+arraydraw"},x0:{valType:"any",editType:"calcIfAutorange+arraydraw"},x1:{valType:"any",editType:"calcIfAutorange+arraydraw"},yref:o({},n.yref,{}),ysizemode:{valType:"enumerated",values:["scaled","pixel"],dflt:"scaled",editType:"calcIfAutorange+arraydraw"},yanchor:{valType:"any",editType:"calcIfAutorange+arraydraw"},y0:{valType:"any",editType:"calcIfAutorange+arraydraw"},y1:{valType:"any",editType:"calcIfAutorange+arraydraw"},path:{valType:"string",editType:"calcIfAutorange+arraydraw"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"arraydraw"},line:{color:o({},a.color,{editType:"arraydraw"}),width:o({},a.width,{editType:"calcIfAutorange+arraydraw"}),dash:o({},i,{editType:"arraydraw"}),editType:"calcIfAutorange+arraydraw"},fillcolor:{valType:"color",dflt:"rgba(0,0,0,0)",editType:"arraydraw"},editType:"arraydraw"})},{"../../lib/extend":157,"../../plot_api/plot_template":197,"../../traces/scatter/attributes":314,"../annotations/attributes":30,"../drawing/attributes":69}],125:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("./constants"),o=t("./helpers");function l(t){return c(t.line.width,t.xsizemode,t.x0,t.x1,t.path,!1)}function s(t){return c(t.line.width,t.ysizemode,t.y0,t.y1,t.path,!0)}function c(t,e,r,a,l,s){var c=t/2,u=s;if("pixel"===e){var f=l?o.extractPathCoords(l,s?i.paramIsY:i.paramIsX):[r,a],d=n.aggNums(Math.max,null,f),p=n.aggNums(Math.min,null,f),h=p<0?Math.abs(p)+c:c,g=d>0?d+c:c;return{ppad:c,ppadplus:u?h:g,ppadminus:u?g:h}}return{ppad:c}}function u(t,e,r,n,a){var l="category"===t.type?t.r2c:t.d2c;if(void 0!==e)return[l(e),l(r)];if(n){var s,c,u,f,d=1/0,p=-1/0,h=n.match(i.segmentRE);for("date"===t.type&&(l=o.decodeDate(l)),s=0;s<h.length;s++)void 0!==(c=a[h[s].charAt(0)].drawn)&&(!(u=h[s].substr(1).match(i.paramRE))||u.length<c||((f=l(u[c]))<d&&(d=f),f>p&&(p=f)));return p>=d?[d,p]:void 0}}e.exports=function(t){var e=t._fullLayout,r=n.filterVisible(e.shapes);if(r.length&&t._fullData.length)for(var o=0;o<r.length;o++){var c,f,d=r[o];if("paper"!==d.xref){var p="pixel"===d.xsizemode?d.xanchor:d.x0,h="pixel"===d.xsizemode?d.xanchor:d.x1;(f=u(c=a.getFromId(t,d.xref),p,h,d.path,i.paramIsX))&&a.expand(c,f,l(d))}if("paper"!==d.yref){var g="pixel"===d.ysizemode?d.yanchor:d.y0,y="pixel"===d.ysizemode?d.yanchor:d.y1;(f=u(c=a.getFromId(t,d.yref),g,y,d.path,i.paramIsY))&&a.expand(c,f,s(d))}}}},{"../../lib":163,"../../plots/cartesian/axes":207,"./constants":126,"./helpers":129}],126:[function(t,e,r){"use strict";e.exports={segmentRE:/[MLHVQCTSZ][^MLHVQCTSZ]*/g,paramRE:/[^\s,]+/g,paramIsX:{M:{0:!0,drawn:0},L:{0:!0,drawn:0},H:{0:!0,drawn:0},V:{},Q:{0:!0,2:!0,drawn:2},C:{0:!0,2:!0,4:!0,drawn:4},T:{0:!0,drawn:0},S:{0:!0,2:!0,drawn:2},Z:{}},paramIsY:{M:{1:!0,drawn:1},L:{1:!0,drawn:1},H:{},V:{0:!0,drawn:0},Q:{1:!0,3:!0,drawn:3},C:{1:!0,3:!0,5:!0,drawn:5},T:{1:!0,drawn:1},S:{1:!0,3:!0,drawn:5},Z:{}},numParams:{M:2,L:2,H:1,V:1,Q:4,C:6,T:2,S:4,Z:0}}},{}],127:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../../plots/array_container_defaults"),o=t("./attributes"),l=t("./helpers");function s(t,e,r){function i(r,a){return n.coerce(t,e,o,r,a)}if(i("visible")){i("layer"),i("opacity"),i("fillcolor"),i("line.color"),i("line.width"),i("line.dash");for(var s=i("type",t.path?"path":"rect"),c=i("xsizemode"),u=i("ysizemode"),f=["x","y"],d=0;d<2;d++){var p,h,g,y=f[d],v=y+"anchor",m="x"===y?c:u,x={_fullLayout:r},b=a.coerceRef(t,e,x,y,"","paper");if("paper"!==b?(p=a.getFromId(x,b),g=l.rangeToShapePosition(p),h=l.shapePositionToRange(p)):h=g=n.identity,"path"!==s){var _=y+"0",w=y+"1",k=t[_],M=t[w];t[_]=h(t[_],!0),t[w]=h(t[w],!0),"pixel"===m?(i(_,0),i(w,10)):(a.coercePosition(e,x,i,b,_,.25),a.coercePosition(e,x,i,b,w,.75)),e[_]=g(e[_]),e[w]=g(e[w]),t[_]=k,t[w]=M}if("pixel"===m){var T=t[v];t[v]=h(t[v],!0),a.coercePosition(e,x,i,b,v,.25),e[v]=g(e[v]),t[v]=T}}"path"===s?i("path"):n.noneOrAll(t,e,["x0","x1","y0","y1"])}}e.exports=function(t,e){i(t,e,{name:"shapes",handleItemDefaults:s})}},{"../../lib":163,"../../plots/array_container_defaults":203,"../../plots/cartesian/axes":207,"./attributes":124,"./helpers":129}],128:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("../../plots/cartesian/axes"),o=t("../color"),l=t("../drawing"),s=t("../../plot_api/plot_template").arrayEditor,c=t("../dragelement"),u=t("../../lib/setcursor"),f=t("./constants"),d=t("./helpers");function p(t,e){t._fullLayout._paperdiv.selectAll('.shapelayer [data-index="'+e+'"]').remove();var r=t._fullLayout.shapes[e]||{};if(r._input&&!1!==r.visible)if("below"!==r.layer)v(t._fullLayout._shapeUpperLayer);else if("paper"===r.xref||"paper"===r.yref)v(t._fullLayout._shapeLowerLayer);else{var p=t._fullLayout._plots[r.xref+r.yref];if(p)v((p.mainplotinfo||p).shapelayer);else v(t._fullLayout._shapeLowerLayer)}function v(p){var v={"data-index":e,"fill-rule":"evenodd",d:g(t,r)},m=r.line.width?r.line.color:"rgba(0,0,0,0)",x=p.append("path").attr(v).style("opacity",r.opacity).call(o.stroke,m).call(o.fill,r.fillcolor).call(l.dashLine,r.line.dash,r.line.width);h(x,t,r),t._context.edits.shapePosition&&function(t,e,r,o,p){var v,m,x,b,_,w,k,M,T,A,L,C,S,O,P,D,z=10,E=10,I="pixel"===r.xsizemode,N="pixel"===r.ysizemode,R="line"===r.type,F="path"===r.type,j=s(t.layout,"shapes",r),B=j.modifyItem,H=i.getFromId(t,r.xref),q=i.getFromId(t,r.yref),V=d.getDataToPixel(t,H),U=d.getDataToPixel(t,q,!0),G=d.getPixelToData(t,H),Y=d.getPixelToData(t,q,!0),X=R?function(){var t=Math.max(r.line.width,10),n=p.append("g").attr("data-index",o);n.append("path").attr("d",e.attr("d")).style({cursor:"move","stroke-width":t,"stroke-opacity":"0"});var a={"fill-opacity":"0"},i=t/2>10?t/2:10;return n.append("circle").attr({"data-line-point":"start-point",cx:I?V(r.xanchor)+r.x0:V(r.x0),cy:N?U(r.yanchor)-r.y0:U(r.y0),r:i}).style(a).classed("cursor-grab",!0),n.append("circle").attr({"data-line-point":"end-point",cx:I?V(r.xanchor)+r.x1:V(r.x1),cy:N?U(r.yanchor)-r.y1:U(r.y1),r:i}).style(a).classed("cursor-grab",!0),n}():e,Z={element:X.node(),gd:t,prepFn:function(n){I&&(_=V(r.xanchor));N&&(w=U(r.yanchor));"path"===r.type?P=r.path:(v=I?r.x0:V(r.x0),m=N?r.y0:U(r.y0),x=I?r.x1:V(r.x1),b=N?r.y1:U(r.y1));v<x?(T=v,S="x0",A=x,O="x1"):(T=x,S="x1",A=v,O="x0");!N&&m<b||N&&m>b?(k=m,L="y0",M=b,C="y1"):(k=b,L="y1",M=m,C="y0");W(n),$(p,r),function(t,e,r){var n=e.xref,a=e.yref,o=i.getFromId(r,n),s=i.getFromId(r,a),c="";"paper"===n||o.autorange||(c+=n);"paper"===a||s.autorange||(c+=a);t.call(l.setClipUrl,c?"clip"+r._fullLayout._uid+c:null)}(e,r,t),Z.moveFn="move"===D?Q:J},doneFn:function(){u(e),K(p),h(e,t,r),n.call("relayout",t,j.getUpdateObj())},clickFn:function(){K(p)}};function W(t){if(R)D="path"===t.target.tagName?"move":"start-point"===t.target.attributes["data-line-point"].value?"resize-over-start-point":"resize-over-end-point";else{var r=Z.element.getBoundingClientRect(),n=r.right-r.left,a=r.bottom-r.top,i=t.clientX-r.left,o=t.clientY-r.top,l=!F&&n>z&&a>E&&!t.shiftKey?c.getCursor(i/n,1-o/a):"move";u(e,l),D=l.split("-")[0]}}function Q(n,a){if("path"===r.type){var i=function(t){return t},o=i,l=i;I?B("xanchor",r.xanchor=G(_+n)):(o=function(t){return G(V(t)+n)},H&&"date"===H.type&&(o=d.encodeDate(o))),N?B("yanchor",r.yanchor=Y(w+a)):(l=function(t){return Y(U(t)+a)},q&&"date"===q.type&&(l=d.encodeDate(l))),B("path",r.path=y(P,o,l))}else I?B("xanchor",r.xanchor=G(_+n)):(B("x0",r.x0=G(v+n)),B("x1",r.x1=G(x+n))),N?B("yanchor",r.yanchor=Y(w+a)):(B("y0",r.y0=Y(m+a)),B("y1",r.y1=Y(b+a)));e.attr("d",g(t,r)),$(p,r)}function J(n,a){if(F){var i=function(t){return t},o=i,l=i;I?B("xanchor",r.xanchor=G(_+n)):(o=function(t){return G(V(t)+n)},H&&"date"===H.type&&(o=d.encodeDate(o))),N?B("yanchor",r.yanchor=Y(w+a)):(l=function(t){return Y(U(t)+a)},q&&"date"===q.type&&(l=d.encodeDate(l))),B("path",r.path=y(P,o,l))}else if(R){if("resize-over-start-point"===D){var s=v+n,c=N?m-a:m+a;B("x0",r.x0=I?s:G(s)),B("y0",r.y0=N?c:Y(c))}else if("resize-over-end-point"===D){var u=x+n,f=N?b-a:b+a;B("x1",r.x1=I?u:G(u)),B("y1",r.y1=N?f:Y(f))}}else{var h=~D.indexOf("n")?k+a:k,j=~D.indexOf("s")?M+a:M,X=~D.indexOf("w")?T+n:T,Z=~D.indexOf("e")?A+n:A;~D.indexOf("n")&&N&&(h=k-a),~D.indexOf("s")&&N&&(j=M-a),(!N&&j-h>E||N&&h-j>E)&&(B(L,r[L]=N?h:Y(h)),B(C,r[C]=N?j:Y(j))),Z-X>z&&(B(S,r[S]=I?X:G(X)),B(O,r[O]=I?Z:G(Z)))}e.attr("d",g(t,r)),$(p,r)}function $(t,e){(I||N)&&function(){var r="path"!==e.type,n=t.selectAll(".visual-cue").data([0]);n.enter().append("path").attr({fill:"#fff","fill-rule":"evenodd",stroke:"#000","stroke-width":1}).classed("visual-cue",!0);var i=V(I?e.xanchor:a.midRange(r?[e.x0,e.x1]:d.extractPathCoords(e.path,f.paramIsX))),o=U(N?e.yanchor:a.midRange(r?[e.y0,e.y1]:d.extractPathCoords(e.path,f.paramIsY)));if(i=d.roundPositionForSharpStrokeRendering(i,1),o=d.roundPositionForSharpStrokeRendering(o,1),I&&N){var l="M"+(i-1-1)+","+(o-1-1)+"h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z";n.attr("d",l)}else if(I){var s="M"+(i-1-1)+","+(o-9-1)+"v18 h2 v-18 Z";n.attr("d",s)}else{var c="M"+(i-9-1)+","+(o-1-1)+"h18 v2 h-18 Z";n.attr("d",c)}}()}function K(t){t.selectAll(".visual-cue").remove()}c.init(Z),X.node().onmousemove=W}(t,x,r,e,p)}}function h(t,e,r){var n=(r.xref+r.yref).replace(/paper/g,"");t.call(l.setClipUrl,n?"clip"+e._fullLayout._uid+n:null)}function g(t,e){var r,n,o,l,s,c,u,p,h=e.type,g=i.getFromId(t,e.xref),y=i.getFromId(t,e.yref),v=t._fullLayout._size;if(g?(r=d.shapePositionToRange(g),n=function(t){return g._offset+g.r2p(r(t,!0))}):n=function(t){return v.l+v.w*t},y?(o=d.shapePositionToRange(y),l=function(t){return y._offset+y.r2p(o(t,!0))}):l=function(t){return v.t+v.h*(1-t)},"path"===h)return g&&"date"===g.type&&(n=d.decodeDate(n)),y&&"date"===y.type&&(l=d.decodeDate(l)),function(t,e,r){var n=t.path,i=t.xsizemode,o=t.ysizemode,l=t.xanchor,s=t.yanchor;return n.replace(f.segmentRE,function(t){var n=0,c=t.charAt(0),u=f.paramIsX[c],d=f.paramIsY[c],p=f.numParams[c],h=t.substr(1).replace(f.paramRE,function(t){return u[n]?t="pixel"===i?e(l)+Number(t):e(t):d[n]&&(t="pixel"===o?r(s)-Number(t):r(t)),++n>p&&(t="X"),t});return n>p&&(h=h.replace(/[\s,]*X.*/,""),a.log("Ignoring extra params in segment "+t)),c+h})}(e,n,l);if("pixel"===e.xsizemode){var m=n(e.xanchor);s=m+e.x0,c=m+e.x1}else s=n(e.x0),c=n(e.x1);if("pixel"===e.ysizemode){var x=l(e.yanchor);u=x-e.y0,p=x-e.y1}else u=l(e.y0),p=l(e.y1);if("line"===h)return"M"+s+","+u+"L"+c+","+p;if("rect"===h)return"M"+s+","+u+"H"+c+"V"+p+"H"+s+"Z";var b=(s+c)/2,_=(u+p)/2,w=Math.abs(b-s),k=Math.abs(_-u),M="A"+w+","+k,T=b+w+","+_;return"M"+T+M+" 0 1,1 "+(b+","+(_-k))+M+" 0 0,1 "+T+"Z"}function y(t,e,r){return t.replace(f.segmentRE,function(t){var n=0,a=t.charAt(0),i=f.paramIsX[a],o=f.paramIsY[a],l=f.numParams[a];return a+t.substr(1).replace(f.paramRE,function(t){return n>=l?t:(i[n]?t=e(t):o[n]&&(t=r(t)),n++,t)})})}e.exports={draw:function(t){var e=t._fullLayout;for(var r in e._shapeUpperLayer.selectAll("path").remove(),e._shapeLowerLayer.selectAll("path").remove(),e._plots){var n=e._plots[r].shapelayer;n&&n.selectAll("path").remove()}for(var a=0;a<e.shapes.length;a++)e.shapes[a].visible&&p(t,a)},drawOne:p}},{"../../lib":163,"../../lib/setcursor":182,"../../plot_api/plot_template":197,"../../plots/cartesian/axes":207,"../../registry":247,"../color":45,"../dragelement":67,"../drawing":70,"./constants":126,"./helpers":129}],129:[function(t,e,r){"use strict";var n=t("./constants"),a=t("../../lib");r.rangeToShapePosition=function(t){return"log"===t.type?t.r2d:function(t){return t}},r.shapePositionToRange=function(t){return"log"===t.type?t.d2r:function(t){return t}},r.decodeDate=function(t){return function(e){return e.replace&&(e=e.replace("_"," ")),t(e)}},r.encodeDate=function(t){return function(e){return t(e).replace(" ","_")}},r.extractPathCoords=function(t,e){var r=[];return t.match(n.segmentRE).forEach(function(t){var i=e[t.charAt(0)].drawn;if(void 0!==i){var o=t.substr(1).match(n.paramRE);!o||o.length<i||r.push(a.cleanNumber(o[i]))}}),r},r.getDataToPixel=function(t,e,n){var a,i=t._fullLayout._size;if(e){var o=r.shapePositionToRange(e);a=function(t){return e._offset+e.r2p(o(t,!0))},"date"===e.type&&(a=r.decodeDate(a))}else a=n?function(t){return i.t+i.h*(1-t)}:function(t){return i.l+i.w*t};return a},r.getPixelToData=function(t,e,n){var a,i=t._fullLayout._size;if(e){var o=r.rangeToShapePosition(e);a=function(t){return o(e.p2r(t-e._offset))}}else a=n?function(t){return 1-(t-i.t)/i.h}:function(t){return(t-i.l)/i.w};return a},r.roundPositionForSharpStrokeRendering=function(t,e){var r=1===Math.round(e%2),n=Math.round(t);return r?n+.5:n}},{"../../lib":163,"./constants":126}],130:[function(t,e,r){"use strict";var n=t("./draw");e.exports={moduleType:"component",name:"shapes",layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),includeBasePlot:t("../../plots/cartesian/include_components")("shapes"),calcAutorange:t("./calc_autorange"),draw:n.draw,drawOne:n.drawOne}},{"../../plots/cartesian/include_components":217,"./attributes":124,"./calc_autorange":125,"./defaults":127,"./draw":128}],131:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),a=t("../../plots/pad_attributes"),i=t("../../lib/extend").extendDeepAll,o=t("../../plot_api/edit_types").overrideAll,l=t("../../plots/animation_attributes"),s=t("../../plot_api/plot_template").templatedArray,c=t("./constants"),u=s("step",{visible:{valType:"boolean",dflt:!0},method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string"},value:{valType:"string"},execute:{valType:"boolean",dflt:!0}});e.exports=o(s("slider",{visible:{valType:"boolean",dflt:!0},active:{valType:"number",min:0,dflt:0},steps:u,lenmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"fraction"},len:{valType:"number",min:0,dflt:1},x:{valType:"number",min:-2,max:3,dflt:0},pad:i({},a,{},{t:{dflt:20}}),xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left"},y:{valType:"number",min:-2,max:3,dflt:0},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},transition:{duration:{valType:"number",min:0,dflt:150},easing:{valType:"enumerated",values:l.transition.easing.values,dflt:"cubic-in-out"}},currentvalue:{visible:{valType:"boolean",dflt:!0},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},offset:{valType:"number",dflt:10},prefix:{valType:"string"},suffix:{valType:"string"},font:n({})},font:n({}),activebgcolor:{valType:"color",dflt:c.gripBgActiveColor},bgcolor:{valType:"color",dflt:c.railBgColor},bordercolor:{valType:"color",dflt:c.railBorderColor},borderwidth:{valType:"number",min:0,dflt:c.railBorderWidth},ticklen:{valType:"number",min:0,dflt:c.tickLength},tickcolor:{valType:"color",dflt:c.tickColor},tickwidth:{valType:"number",min:0,dflt:1},minorticklen:{valType:"number",min:0,dflt:c.minorTickLength}}),"arraydraw","from-root")},{"../../lib/extend":157,"../../plot_api/edit_types":190,"../../plot_api/plot_template":197,"../../plots/animation_attributes":202,"../../plots/font_attributes":233,"../../plots/pad_attributes":238,"./constants":132}],132:[function(t,e,r){"use strict";e.exports={name:"sliders",containerClassName:"slider-container",groupClassName:"slider-group",inputAreaClass:"slider-input-area",railRectClass:"slider-rail-rect",railTouchRectClass:"slider-rail-touch-rect",gripRectClass:"slider-grip-rect",tickRectClass:"slider-tick-rect",inputProxyClass:"slider-input-proxy",labelsClass:"slider-labels",labelGroupClass:"slider-label-group",labelClass:"slider-label",currentValueClass:"slider-current-value",railHeight:5,menuIndexAttrName:"slider-active-index",autoMarginIdRoot:"slider-",minWidth:30,minHeight:30,textPadX:40,arrowOffsetX:4,railRadius:2,railWidth:5,railBorder:4,railBorderWidth:1,railBorderColor:"#bec8d9",railBgColor:"#f8fafc",railInset:8,stepInset:10,gripRadius:10,gripWidth:20,gripHeight:20,gripBorder:20,gripBorderWidth:1,gripBorderColor:"#bec8d9",gripBgColor:"#f6f8fa",gripBgActiveColor:"#dbdde0",labelPadding:8,labelOffset:0,tickWidth:1,tickColor:"#333",tickOffset:25,tickLength:7,minorTickOffset:25,minorTickColor:"#333",minorTickLength:4,currentValuePadding:8,currentValueInset:0}},{}],133:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/array_container_defaults"),i=t("./attributes"),o=t("./constants").name,l=i.steps;function s(t,e,r){function o(r,a){return n.coerce(t,e,i,r,a)}for(var l=a(t,e,{name:"steps",handleItemDefaults:c}),s=0,u=0;u<l.length;u++)l[u].visible&&s++;if(s<2?e.visible=!1:o("visible")){e._stepCount=s;var f=e._visibleSteps=n.filterVisible(l);(l[o("active")]||{}).visible||(e.active=f[0]._index),o("x"),o("y"),n.noneOrAll(t,e,["x","y"]),o("xanchor"),o("yanchor"),o("len"),o("lenmode"),o("pad.t"),o("pad.r"),o("pad.b"),o("pad.l"),n.coerceFont(o,"font",r.font),o("currentvalue.visible")&&(o("currentvalue.xanchor"),o("currentvalue.prefix"),o("currentvalue.suffix"),o("currentvalue.offset"),n.coerceFont(o,"currentvalue.font",e.font)),o("transition.duration"),o("transition.easing"),o("bgcolor"),o("activebgcolor"),o("bordercolor"),o("borderwidth"),o("ticklen"),o("tickwidth"),o("tickcolor"),o("minorticklen")}}function c(t,e){function r(r,a){return n.coerce(t,e,l,r,a)}if("skip"===t.method||Array.isArray(t.args)?r("visible"):e.visible=!1){r("method"),r("args");var a=r("label","step-"+e._index);r("value",a),r("execute")}}e.exports=function(t,e){a(t,e,{name:o,handleItemDefaults:s})}},{"../../lib":163,"../../plots/array_container_defaults":203,"./attributes":131,"./constants":132}],134:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../plots/plots"),i=t("../color"),o=t("../drawing"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("../legend/anchor_utils"),u=t("../../plot_api/plot_template").arrayEditor,f=t("./constants"),d=t("../../constants/alignment"),p=d.LINE_SPACING,h=d.FROM_TL,g=d.FROM_BR;function y(t){return f.autoMarginIdRoot+t._index}function v(t){return t._index}function m(t,e){var r=o.tester.selectAll("g."+f.labelGroupClass).data(e._visibleSteps);r.enter().append("g").classed(f.labelGroupClass,!0);var i=0,l=0;r.each(function(t){var r=_(n.select(this),{step:t},e).node();if(r){var a=o.bBox(r);l=Math.max(l,a.height),i=Math.max(i,a.width)}}),r.remove();var u=e._dims={};u.inputAreaWidth=Math.max(f.railWidth,f.gripHeight);var d=t._fullLayout._size;u.lx=d.l+d.w*e.x,u.ly=d.t+d.h*(1-e.y),"fraction"===e.lenmode?u.outerLength=Math.round(d.w*e.len):u.outerLength=e.len,u.inputAreaStart=0,u.inputAreaLength=Math.round(u.outerLength-e.pad.l-e.pad.r);var p=(u.inputAreaLength-2*f.stepInset)/(e._stepCount-1),v=i+f.labelPadding;if(u.labelStride=Math.max(1,Math.ceil(v/p)),u.labelHeight=l,u.currentValueMaxWidth=0,u.currentValueHeight=0,u.currentValueTotalHeight=0,u.currentValueMaxLines=1,e.currentvalue.visible){var m=o.tester.append("g");r.each(function(t){var r=x(m,e,t.label),n=r.node()&&o.bBox(r.node())||{width:0,height:0},a=s.lineCount(r);u.currentValueMaxWidth=Math.max(u.currentValueMaxWidth,Math.ceil(n.width)),u.currentValueHeight=Math.max(u.currentValueHeight,Math.ceil(n.height)),u.currentValueMaxLines=Math.max(u.currentValueMaxLines,a)}),u.currentValueTotalHeight=u.currentValueHeight+e.currentvalue.offset,m.remove()}u.height=u.currentValueTotalHeight+f.tickOffset+e.ticklen+f.labelOffset+u.labelHeight+e.pad.t+e.pad.b;var b="left";c.isRightAnchor(e)&&(u.lx-=u.outerLength,b="right"),c.isCenterAnchor(e)&&(u.lx-=u.outerLength/2,b="center");var w="top";c.isBottomAnchor(e)&&(u.ly-=u.height,w="bottom"),c.isMiddleAnchor(e)&&(u.ly-=u.height/2,w="middle"),u.outerLength=Math.ceil(u.outerLength),u.height=Math.ceil(u.height),u.lx=Math.round(u.lx),u.ly=Math.round(u.ly);var k={y:e.y,b:u.height*g[w],t:u.height*h[w]};"fraction"===e.lenmode?(k.l=0,k.xl=e.x-e.len*h[b],k.r=0,k.xr=e.x+e.len*g[b]):(k.x=e.x,k.l=u.outerLength*h[b],k.r=u.outerLength*g[b]),a.autoMargin(t,y(e),k)}function x(t,e,r){if(e.currentvalue.visible){var n,a,i=e._dims;switch(e.currentvalue.xanchor){case"right":n=i.inputAreaLength-f.currentValueInset-i.currentValueMaxWidth,a="left";break;case"center":n=.5*i.inputAreaLength,a="middle";break;default:n=f.currentValueInset,a="left"}var c=l.ensureSingle(t,"text",f.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":a,"data-notex":1})}),u=e.currentvalue.prefix?e.currentvalue.prefix:"";if("string"==typeof r)u+=r;else u+=e.steps[e.active].label;e.currentvalue.suffix&&(u+=e.currentvalue.suffix),c.call(o.font,e.currentvalue.font).text(u).call(s.convertToTspans,e._gd);var d=s.lineCount(c),h=(i.currentValueMaxLines+1-d)*e.currentvalue.font.size*p;return s.positionText(c,n,h),c}}function b(t,e,r){l.ensureSingle(t,"rect",f.gripRectClass,function(n){n.call(T,e,t,r).style("pointer-events","all")}).attr({width:f.gripWidth,height:f.gripHeight,rx:f.gripRadius,ry:f.gripRadius}).call(i.stroke,r.bordercolor).call(i.fill,r.bgcolor).style("stroke-width",r.borderwidth+"px")}function _(t,e,r){var n=l.ensureSingle(t,"text",f.labelClass,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"middle","data-notex":1})});return n.call(o.font,r.font).text(e.step.label).call(s.convertToTspans,r._gd),n}function w(t,e){var r=l.ensureSingle(t,"g",f.labelsClass),a=e._dims,i=r.selectAll("g."+f.labelGroupClass).data(a.labelSteps);i.enter().append("g").classed(f.labelGroupClass,!0),i.exit().remove(),i.each(function(t){var r=n.select(this);r.call(_,t,e),o.setTranslate(r,C(e,t.fraction),f.tickOffset+e.ticklen+e.font.size*p+f.labelOffset+a.currentValueTotalHeight)})}function k(t,e,r,n,a){var i=Math.round(n*(r._stepCount-1)),o=r._visibleSteps[i]._index;o!==r.active&&M(t,e,r,o,!0,a)}function M(t,e,r,n,i,o){var l=r.active;r.active=n,u(t.layout,f.name,r).applyUpdate("active",n);var s=r.steps[r.active];e.call(L,r,o),e.call(x,r),t.emit("plotly_sliderchange",{slider:r,step:r.steps[r.active],interaction:i,previousActive:l}),s&&s.method&&i&&(e._nextMethod?(e._nextMethod.step=s,e._nextMethod.doCallback=i,e._nextMethod.doTransition=o):(e._nextMethod={step:s,doCallback:i,doTransition:o},e._nextMethodRaf=window.requestAnimationFrame(function(){var r=e._nextMethod.step;r.method&&(r.execute&&a.executeAPICommand(t,r.method,r.args),e._nextMethod=null,e._nextMethodRaf=null)})))}function T(t,e,r){var a=r.node(),o=n.select(e);function l(){return r.data()[0]}t.on("mousedown",function(){var t=l();e.emit("plotly_sliderstart",{slider:t});var s=r.select("."+f.gripRectClass);n.event.stopPropagation(),n.event.preventDefault(),s.call(i.fill,t.activebgcolor);var c=S(t,n.mouse(a)[0]);k(e,r,t,c,!0),t._dragging=!0,o.on("mousemove",function(){var t=l(),i=S(t,n.mouse(a)[0]);k(e,r,t,i,!1)}),o.on("mouseup",function(){var t=l();t._dragging=!1,s.call(i.fill,t.bgcolor),o.on("mouseup",null),o.on("mousemove",null),e.emit("plotly_sliderend",{slider:t,step:t.steps[t.active]})})})}function A(t,e){var r=t.selectAll("rect."+f.tickRectClass).data(e._visibleSteps),a=e._dims;r.enter().append("rect").classed(f.tickRectClass,!0),r.exit().remove(),r.attr({width:e.tickwidth+"px","shape-rendering":"crispEdges"}),r.each(function(t,r){var l=r%a.labelStride==0,s=n.select(this);s.attr({height:l?e.ticklen:e.minorticklen}).call(i.fill,e.tickcolor),o.setTranslate(s,C(e,r/(e._stepCount-1))-.5*e.tickwidth,(l?f.tickOffset:f.minorTickOffset)+a.currentValueTotalHeight)})}function L(t,e,r){for(var n=t.select("rect."+f.gripRectClass),a=0,i=0;i<e._stepCount;i++)if(e._visibleSteps[i]._index===e.active){a=i;break}var o=C(e,a/(e._stepCount-1));if(!e._invokingCommand){var l=n;r&&e.transition.duration>0&&(l=l.transition().duration(e.transition.duration).ease(e.transition.easing)),l.attr("transform","translate("+(o-.5*f.gripWidth)+","+e._dims.currentValueTotalHeight+")")}}function C(t,e){var r=t._dims;return r.inputAreaStart+f.stepInset+(r.inputAreaLength-2*f.stepInset)*Math.min(1,Math.max(0,e))}function S(t,e){var r=t._dims;return Math.min(1,Math.max(0,(e-f.stepInset-r.inputAreaStart)/(r.inputAreaLength-2*f.stepInset-2*r.inputAreaStart)))}function O(t,e,r){var n=r._dims,a=l.ensureSingle(t,"rect",f.railTouchRectClass,function(n){n.call(T,e,t,r).style("pointer-events","all")});a.attr({width:n.inputAreaLength,height:Math.max(n.inputAreaWidth,f.tickOffset+r.ticklen+n.labelHeight)}).call(i.fill,r.bgcolor).attr("opacity",0),o.setTranslate(a,0,n.currentValueTotalHeight)}function P(t,e){var r=e._dims,n=r.inputAreaLength-2*f.railInset,a=l.ensureSingle(t,"rect",f.railRectClass);a.attr({width:n,height:f.railWidth,rx:f.railRadius,ry:f.railRadius,"shape-rendering":"crispEdges"}).call(i.stroke,e.bordercolor).call(i.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px"),o.setTranslate(a,f.railInset,.5*(r.inputAreaWidth-f.railWidth)+r.currentValueTotalHeight)}e.exports=function(t){var e=t._fullLayout,r=function(t,e){for(var r=t[f.name],n=[],a=0;a<r.length;a++){var i=r[a];i.visible&&(i._gd=e,n.push(i))}return n}(e,t),i=e._infolayer.selectAll("g."+f.containerClassName).data(r.length>0?[0]:[]);function l(e){e._commandObserver&&(e._commandObserver.remove(),delete e._commandObserver),a.autoMargin(t,y(e))}if(i.enter().append("g").classed(f.containerClassName,!0).style("cursor","ew-resize"),i.exit().each(function(){n.select(this).selectAll("g."+f.groupClassName).each(l)}).remove(),0!==r.length){var s=i.selectAll("g."+f.groupClassName).data(r,v);s.enter().append("g").classed(f.groupClassName,!0),s.exit().each(l).remove();for(var c=0;c<r.length;c++){var u=r[c];m(t,u)}s.each(function(e){var r=n.select(this);!function(t){var e=t._dims;e.labelSteps=[];for(var r=t._stepCount,n=0;n<r;n+=e.labelStride)e.labelSteps.push({fraction:n/(r-1),step:t._visibleSteps[n]})}(e),a.manageCommandObserver(t,e,e._visibleSteps,function(e){var n=r.data()[0];n.active!==e.index&&(n._dragging||M(t,r,n,e.index,!1,!0))}),function(t,e,r){(r.steps[r.active]||{}).visible||(r.active=r._visibleSteps[0]._index);e.call(x,r).call(P,r).call(w,r).call(A,r).call(O,t,r).call(b,t,r);var n=r._dims;o.setTranslate(e,n.lx+r.pad.l,n.ly+r.pad.t),e.call(L,r,!1),e.call(x,r)}(t,n.select(this),e)})}}},{"../../constants/alignment":143,"../../lib":163,"../../lib/svg_text_utils":184,"../../plot_api/plot_template":197,"../../plots/plots":239,"../color":45,"../drawing":70,"../legend/anchor_utils":97,"./constants":132,d3:10}],135:[function(t,e,r){"use strict";var n=t("./constants");e.exports={moduleType:"component",name:n.name,layoutAttributes:t("./attributes"),supplyLayoutDefaults:t("./defaults"),draw:t("./draw")}},{"./attributes":131,"./constants":132,"./defaults":133,"./draw":134}],136:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../../plots/plots"),o=t("../../registry"),l=t("../../lib"),s=t("../drawing"),c=t("../color"),u=t("../../lib/svg_text_utils"),f=t("../../constants/interactions");e.exports={draw:function(t,e,r){var p,h=r.propContainer,g=r.propName,y=r.placeholder,v=r.traceIndex,m=r.avoid||{},x=r.attributes,b=r.transform,_=r.containerGroup,w=t._fullLayout,k=h.titlefont||{},M=k.family,T=k.size,A=k.color,L=1,C=!1,S=(h.title||"").trim();"title"===g?p="titleText":-1!==g.indexOf("axis")?p="axisTitleText":g.indexOf(!0)&&(p="colorbarTitleText");var O=t._context.edits[p];""===S?L=0:S.replace(d," % ")===y.replace(d," % ")&&(L=.2,C=!0,O||(S=""));var P=S||O;_||(_=l.ensureSingle(w._infolayer,"g","g-"+e));var D=_.selectAll("text").data(P?[0]:[]);if(D.enter().append("text"),D.text(S).attr("class",e),D.exit().remove(),!P)return _;function z(t){l.syncOrAsync([E,I],t)}function E(e){var r;return b?(r="",b.rotate&&(r+="rotate("+[b.rotate,x.x,x.y]+")"),b.offset&&(r+="translate(0, "+b.offset+")")):r=null,e.attr("transform",r),e.style({"font-family":M,"font-size":n.round(T,2)+"px",fill:c.rgb(A),opacity:L*c.opacity(A),"font-weight":i.fontWeight}).attr(x).call(u.convertToTspans,t),i.previousPromises(t)}function I(t){var e=n.select(t.node().parentNode);if(m&&m.selection&&m.side&&S){e.attr("transform",null);var r=0,i={left:"right",right:"left",top:"bottom",bottom:"top"}[m.side],o=-1!==["left","top"].indexOf(m.side)?-1:1,c=a(m.pad)?m.pad:2,u=s.bBox(e.node()),f={left:0,top:0,right:w.width,bottom:w.height},d=m.maxShift||(f[m.side]-u[m.side])*("left"===m.side||"top"===m.side?-1:1);if(d<0)r=d;else{var p=m.offsetLeft||0,h=m.offsetTop||0;u.left-=p,u.right-=p,u.top-=h,u.bottom-=h,m.selection.each(function(){var t=s.bBox(this);l.bBoxIntersect(u,t,c)&&(r=Math.max(r,o*(t[m.side]-u[i])+c))}),r=Math.min(d,r)}if(r>0||d<0){var g={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[m.side];e.attr("transform","translate("+g+")")}}}D.call(z),O&&(S?D.on(".opacity",null):(L=0,C=!0,D.text(y).on("mouseover.opacity",function(){n.select(this).transition().duration(f.SHOW_PLACEHOLDER).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(f.HIDE_PLACEHOLDER).style("opacity",0)})),D.call(u.makeEditable,{gd:t}).on("edit",function(e){void 0!==v?o.call("restyle",t,g,e,v):o.call("relayout",t,g,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(z)}).on("input",function(t){this.text(t||" ").call(u.positionText,x.x,x.y)}));return D.classed("js-placeholder",C),_}};var d=/ [XY][0-9]* /},{"../../constants/interactions":144,"../../lib":163,"../../lib/svg_text_utils":184,"../../plots/plots":239,"../../registry":247,"../color":45,"../drawing":70,d3:10,"fast-isnumeric":13}],137:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),a=t("../color/attributes"),i=t("../../lib/extend").extendFlat,o=t("../../plot_api/edit_types").overrideAll,l=t("../../plots/pad_attributes"),s=t("../../plot_api/plot_template").templatedArray,c=s("button",{visible:{valType:"boolean"},method:{valType:"enumerated",values:["restyle","relayout","animate","update","skip"],dflt:"restyle"},args:{valType:"info_array",freeLength:!0,items:[{valType:"any"},{valType:"any"},{valType:"any"}]},label:{valType:"string",dflt:""},execute:{valType:"boolean",dflt:!0}});e.exports=o(s("updatemenu",{_arrayAttrRegexps:[/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],visible:{valType:"boolean"},type:{valType:"enumerated",values:["dropdown","buttons"],dflt:"dropdown"},direction:{valType:"enumerated",values:["left","right","up","down"],dflt:"down"},active:{valType:"integer",min:-1,dflt:0},showactive:{valType:"boolean",dflt:!0},buttons:c,x:{valType:"number",min:-2,max:3,dflt:-.05},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"right"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"top"},pad:i({},l,{}),font:n({}),bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:a.borderLine},borderwidth:{valType:"number",min:0,dflt:1,editType:"arraydraw"}}),"arraydraw","from-root")},{"../../lib/extend":157,"../../plot_api/edit_types":190,"../../plot_api/plot_template":197,"../../plots/font_attributes":233,"../../plots/pad_attributes":238,"../color/attributes":44}],138:[function(t,e,r){"use strict";e.exports={name:"updatemenus",containerClassName:"updatemenu-container",headerGroupClassName:"updatemenu-header-group",headerClassName:"updatemenu-header",headerArrowClassName:"updatemenu-header-arrow",dropdownButtonGroupClassName:"updatemenu-dropdown-button-group",dropdownButtonClassName:"updatemenu-dropdown-button",buttonClassName:"updatemenu-button",itemRectClassName:"updatemenu-item-rect",itemTextClassName:"updatemenu-item-text",menuIndexAttrName:"updatemenu-active-index",autoMarginIdRoot:"updatemenu-",blankHeaderOpts:{label:" "},minWidth:30,minHeight:30,textPadX:24,arrowPadX:16,rx:2,ry:2,textOffsetX:12,textOffsetY:3,arrowOffsetX:4,gapButtonHeader:5,gapButton:2,activeColor:"#F4FAFF",hoverColor:"#F4FAFF",arrowSymbol:{left:"\u25c4",right:"\u25ba",up:"\u25b2",down:"\u25bc"}}},{}],139:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/array_container_defaults"),i=t("./attributes"),o=t("./constants").name,l=i.buttons;function s(t,e,r){function o(r,a){return n.coerce(t,e,i,r,a)}o("visible",a(t,e,{name:"buttons",handleItemDefaults:c}).length>0)&&(o("active"),o("direction"),o("type"),o("showactive"),o("x"),o("y"),n.noneOrAll(t,e,["x","y"]),o("xanchor"),o("yanchor"),o("pad.t"),o("pad.r"),o("pad.b"),o("pad.l"),n.coerceFont(o,"font",r.font),o("bgcolor",r.paper_bgcolor),o("bordercolor"),o("borderwidth"))}function c(t,e){function r(r,a){return n.coerce(t,e,l,r,a)}r("visible","skip"===t.method||Array.isArray(t.args))&&(r("method"),r("args"),r("label"),r("execute"))}e.exports=function(t,e){a(t,e,{name:o,handleItemDefaults:s})}},{"../../lib":163,"../../plots/array_container_defaults":203,"./attributes":137,"./constants":138}],140:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../plots/plots"),i=t("../color"),o=t("../drawing"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("../legend/anchor_utils"),u=t("../../plot_api/plot_template").arrayEditor,f=t("../../constants/alignment").LINE_SPACING,d=t("./constants"),p=t("./scrollbox");function h(t){return t._index}function g(t,e){return+t.attr(d.menuIndexAttrName)===e._index}function y(t,e,r,n,a,i,o,l){e.active=o,u(t.layout,d.name,e).applyUpdate("active",o),"buttons"===e.type?m(t,n,null,null,e):"dropdown"===e.type&&(a.attr(d.menuIndexAttrName,"-1"),v(t,n,a,i,e),l||m(t,n,a,i,e))}function v(t,e,r,n,a){var i=l.ensureSingle(e,"g",d.headerClassName,function(t){t.style("pointer-events","all")}),s=a._dims,c=a.active,u=a.buttons[c]||d.blankHeaderOpts,f={y:a.pad.t,yPad:0,x:a.pad.l,xPad:0,index:0},p={width:s.headerWidth,height:s.headerHeight};i.call(x,a,u,t).call(L,a,f,p),l.ensureSingle(e,"text",d.headerArrowClassName,function(t){t.classed("user-select-none",!0).attr("text-anchor","end").call(o.font,a.font).text(d.arrowSymbol[a.direction])}).attr({x:s.headerWidth-d.arrowOffsetX+a.pad.l,y:s.headerHeight/2+d.textOffsetY+a.pad.t}),i.on("click",function(){r.call(C,String(g(r,a)?-1:a._index)),m(t,e,r,n,a)}),i.on("mouseover",function(){i.call(k)}),i.on("mouseout",function(){i.call(M,a)}),o.setTranslate(e,s.lx,s.ly)}function m(t,e,r,i,o){r||(r=e).attr("pointer-events","all");var s=function(t){return-1==+t.attr(d.menuIndexAttrName)}(r)&&"buttons"!==o.type?[]:o.buttons,c="dropdown"===o.type?d.dropdownButtonClassName:d.buttonClassName,u=r.selectAll("g."+c).data(l.filterVisible(s)),f=u.enter().append("g").classed(c,!0),p=u.exit();"dropdown"===o.type?(f.attr("opacity","0").transition().attr("opacity","1"),p.transition().attr("opacity","0").remove()):p.remove();var h=0,g=0,v=o._dims,m=-1!==["up","down"].indexOf(o.direction);"dropdown"===o.type&&(m?g=v.headerHeight+d.gapButtonHeader:h=v.headerWidth+d.gapButtonHeader),"dropdown"===o.type&&"up"===o.direction&&(g=-d.gapButtonHeader+d.gapButton-v.openHeight),"dropdown"===o.type&&"left"===o.direction&&(h=-d.gapButtonHeader+d.gapButton-v.openWidth);var b={x:v.lx+h+o.pad.l,y:v.ly+g+o.pad.t,yPad:d.gapButton,xPad:d.gapButton,index:0},_={l:b.x+o.borderwidth,t:b.y+o.borderwidth};u.each(function(l,s){var c=n.select(this);c.call(x,o,l,t).call(L,o,b),c.on("click",function(){n.event.defaultPrevented||(y(t,o,0,e,r,i,s),l.execute&&a.executeAPICommand(t,l.method,l.args),t.emit("plotly_buttonclicked",{menu:o,button:l,active:o.active}))}),c.on("mouseover",function(){c.call(k)}),c.on("mouseout",function(){c.call(M,o),u.call(w,o)})}),u.call(w,o),m?(_.w=Math.max(v.openWidth,v.headerWidth),_.h=b.y-_.t):(_.w=b.x-_.l,_.h=Math.max(v.openHeight,v.headerHeight)),_.direction=o.direction,i&&(u.size()?function(t,e,r,n,a,i){var o,l,s,c=a.direction,u="up"===c||"down"===c,f=a._dims,p=a.active;if(u)for(l=0,s=0;s<p;s++)l+=f.heights[s]+d.gapButton;else for(o=0,s=0;s<p;s++)o+=f.widths[s]+d.gapButton;n.enable(i,o,l),n.hbar&&n.hbar.attr("opacity","0").transition().attr("opacity","1");n.vbar&&n.vbar.attr("opacity","0").transition().attr("opacity","1")}(0,0,0,i,o,_):function(t){var e=!!t.hbar,r=!!t.vbar;e&&t.hbar.transition().attr("opacity","0").each("end",function(){e=!1,r||t.disable()});r&&t.vbar.transition().attr("opacity","0").each("end",function(){r=!1,e||t.disable()})}(i))}function x(t,e,r,n){t.call(b,e).call(_,e,r,n)}function b(t,e){l.ensureSingle(t,"rect",d.itemRectClassName,function(t){t.attr({rx:d.rx,ry:d.ry,"shape-rendering":"crispEdges"})}).call(i.stroke,e.bordercolor).call(i.fill,e.bgcolor).style("stroke-width",e.borderwidth+"px")}function _(t,e,r,n){l.ensureSingle(t,"text",d.itemTextClassName,function(t){t.classed("user-select-none",!0).attr({"text-anchor":"start","data-notex":1})}).call(o.font,e.font).text(r.label).call(s.convertToTspans,n)}function w(t,e){var r=e.active;t.each(function(t,a){var o=n.select(this);a===r&&e.showactive&&o.select("rect."+d.itemRectClassName).call(i.fill,d.activeColor)})}function k(t){t.select("rect."+d.itemRectClassName).call(i.fill,d.hoverColor)}function M(t,e){t.select("rect."+d.itemRectClassName).call(i.fill,e.bgcolor)}function T(t,e){var r=e._dims={width1:0,height1:0,heights:[],widths:[],totalWidth:0,totalHeight:0,openWidth:0,openHeight:0,lx:0,ly:0},i=o.tester.selectAll("g."+d.dropdownButtonClassName).data(l.filterVisible(e.buttons));i.enter().append("g").classed(d.dropdownButtonClassName,!0);var u=-1!==["up","down"].indexOf(e.direction);i.each(function(a,i){var l=n.select(this);l.call(x,e,a,t);var c=l.select("."+d.itemTextClassName),p=c.node()&&o.bBox(c.node()).width,h=Math.max(p+d.textPadX,d.minWidth),g=e.font.size*f,y=s.lineCount(c),v=Math.max(g*y,d.minHeight)+d.textOffsetY;v=Math.ceil(v),h=Math.ceil(h),r.widths[i]=h,r.heights[i]=v,r.height1=Math.max(r.height1,v),r.width1=Math.max(r.width1,h),u?(r.totalWidth=Math.max(r.totalWidth,h),r.openWidth=r.totalWidth,r.totalHeight+=v+d.gapButton,r.openHeight+=v+d.gapButton):(r.totalWidth+=h+d.gapButton,r.openWidth+=h+d.gapButton,r.totalHeight=Math.max(r.totalHeight,v),r.openHeight=r.totalHeight)}),u?r.totalHeight-=d.gapButton:r.totalWidth-=d.gapButton,r.headerWidth=r.width1+d.arrowPadX,r.headerHeight=r.height1,"dropdown"===e.type&&(u?(r.width1+=d.arrowPadX,r.totalHeight=r.height1):r.totalWidth=r.width1,r.totalWidth+=d.arrowPadX),i.remove();var p=r.totalWidth+e.pad.l+e.pad.r,h=r.totalHeight+e.pad.t+e.pad.b,g=t._fullLayout._size;r.lx=g.l+g.w*e.x,r.ly=g.t+g.h*(1-e.y);var y="left";c.isRightAnchor(e)&&(r.lx-=p,y="right"),c.isCenterAnchor(e)&&(r.lx-=p/2,y="center");var v="top";c.isBottomAnchor(e)&&(r.ly-=h,v="bottom"),c.isMiddleAnchor(e)&&(r.ly-=h/2,v="middle"),r.totalWidth=Math.ceil(r.totalWidth),r.totalHeight=Math.ceil(r.totalHeight),r.lx=Math.round(r.lx),r.ly=Math.round(r.ly),a.autoMargin(t,A(e),{x:e.x,y:e.y,l:p*({right:1,center:.5}[y]||0),r:p*({left:1,center:.5}[y]||0),b:h*({top:1,middle:.5}[v]||0),t:h*({bottom:1,middle:.5}[v]||0)})}function A(t){return d.autoMarginIdRoot+t._index}function L(t,e,r,n){n=n||{};var a=t.select("."+d.itemRectClassName),i=t.select("."+d.itemTextClassName),l=e.borderwidth,c=r.index,u=e._dims;o.setTranslate(t,l+r.x,l+r.y);var p=-1!==["up","down"].indexOf(e.direction),h=n.height||(p?u.heights[c]:u.height1);a.attr({x:0,y:0,width:n.width||(p?u.width1:u.widths[c]),height:h});var g=e.font.size*f,y=(s.lineCount(i)-1)*g/2;s.positionText(i,d.textOffsetX,h/2-y+d.textOffsetY),p?r.y+=u.heights[c]+r.yPad:r.x+=u.widths[c]+r.xPad,r.index++}function C(t,e){t.attr(d.menuIndexAttrName,e||"-1").selectAll("g."+d.dropdownButtonClassName).remove()}e.exports=function(t){var e=t._fullLayout,r=l.filterVisible(e[d.name]);function i(e){a.autoMargin(t,A(e))}var o=e._menulayer.selectAll("g."+d.containerClassName).data(r.length>0?[0]:[]);if(o.enter().append("g").classed(d.containerClassName,!0).style("cursor","pointer"),o.exit().each(function(){n.select(this).selectAll("g."+d.headerGroupClassName).each(i)}).remove(),0!==r.length){var s=o.selectAll("g."+d.headerGroupClassName).data(r,h);s.enter().append("g").classed(d.headerGroupClassName,!0);for(var c=l.ensureSingle(o,"g",d.dropdownButtonGroupClassName,function(t){t.style("pointer-events","all")}),u=0;u<r.length;u++){var f=r[u];T(t,f)}var x="updatemenus"+e._uid,b=new p(t,c,x);s.enter().size()&&(c.node().parentNode.appendChild(c.node()),c.call(C)),s.exit().each(function(t){c.call(C),i(t)}).remove(),s.each(function(e){var r=n.select(this),i="dropdown"===e.type?c:null;a.manageCommandObserver(t,e,e.buttons,function(n){y(t,e,e.buttons[n.index],r,i,b,n.index,!0)}),"dropdown"===e.type?(v(t,r,c,b,e),g(c,e)&&m(t,r,c,b,e)):m(t,r,null,null,e)})}}},{"../../constants/alignment":143,"../../lib":163,"../../lib/svg_text_utils":184,"../../plot_api/plot_template":197,"../../plots/plots":239,"../color":45,"../drawing":70,"../legend/anchor_utils":97,"./constants":138,"./scrollbox":142,d3:10}],141:[function(t,e,r){arguments[4][135][0].apply(r,arguments)},{"./attributes":137,"./constants":138,"./defaults":139,"./draw":140,dup:135}],142:[function(t,e,r){"use strict";e.exports=l;var n=t("d3"),a=t("../color"),i=t("../drawing"),o=t("../../lib");function l(t,e,r){this.gd=t,this.container=e,this.id=r,this.position=null,this.translateX=null,this.translateY=null,this.hbar=null,this.vbar=null,this.bg=this.container.selectAll("rect.scrollbox-bg").data([0]),this.bg.exit().on(".drag",null).on("wheel",null).remove(),this.bg.enter().append("rect").classed("scrollbox-bg",!0).style("pointer-events","all").attr({opacity:0,x:0,y:0,width:0,height:0})}l.barWidth=2,l.barLength=20,l.barRadius=2,l.barPad=1,l.barColor="#808BA4",l.prototype.enable=function(t,e,r){var o=this.gd._fullLayout,s=o.width,c=o.height;this.position=t;var u,f,d,p,h=this.position.l,g=this.position.w,y=this.position.t,v=this.position.h,m=this.position.direction,x="down"===m,b="left"===m,_="up"===m,w=g,k=v;x||b||"right"===m||_||(this.position.direction="down",x=!0),x||_?(f=(u=h)+w,x?(d=y,k=(p=Math.min(d+k,c))-d):k=(p=y+k)-(d=Math.max(p-k,0))):(p=(d=y)+k,b?w=(f=h+w)-(u=Math.max(f-w,0)):(u=h,w=(f=Math.min(u+w,s))-u)),this._box={l:u,t:d,w:w,h:k};var M=g>w,T=l.barLength+2*l.barPad,A=l.barWidth+2*l.barPad,L=h,C=y+v;C+A>c&&(C=c-A);var S=this.container.selectAll("rect.scrollbar-horizontal").data(M?[0]:[]);S.exit().on(".drag",null).remove(),S.enter().append("rect").classed("scrollbar-horizontal",!0).call(a.fill,l.barColor),M?(this.hbar=S.attr({rx:l.barRadius,ry:l.barRadius,x:L,y:C,width:T,height:A}),this._hbarXMin=L+T/2,this._hbarTranslateMax=w-T):(delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax);var O=v>k,P=l.barWidth+2*l.barPad,D=l.barLength+2*l.barPad,z=h+g,E=y;z+P>s&&(z=s-P);var I=this.container.selectAll("rect.scrollbar-vertical").data(O?[0]:[]);I.exit().on(".drag",null).remove(),I.enter().append("rect").classed("scrollbar-vertical",!0).call(a.fill,l.barColor),O?(this.vbar=I.attr({rx:l.barRadius,ry:l.barRadius,x:z,y:E,width:P,height:D}),this._vbarYMin=E+D/2,this._vbarTranslateMax=k-D):(delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax);var N=this.id,R=u-.5,F=O?f+P+.5:f+.5,j=d-.5,B=M?p+A+.5:p+.5,H=o._topdefs.selectAll("#"+N).data(M||O?[0]:[]);if(H.exit().remove(),H.enter().append("clipPath").attr("id",N).append("rect"),M||O?(this._clipRect=H.select("rect").attr({x:Math.floor(R),y:Math.floor(j),width:Math.ceil(F)-Math.floor(R),height:Math.ceil(B)-Math.floor(j)}),this.container.call(i.setClipUrl,N),this.bg.attr({x:h,y:y,width:g,height:v})):(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(i.setClipUrl,null),delete this._clipRect),M||O){var q=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault()}).on("drag",this._onBoxDrag.bind(this));this.container.on("wheel",null).on("wheel",this._onBoxWheel.bind(this)).on(".drag",null).call(q);var V=n.behavior.drag().on("dragstart",function(){n.event.sourceEvent.preventDefault(),n.event.sourceEvent.stopPropagation()}).on("drag",this._onBarDrag.bind(this));M&&this.hbar.on(".drag",null).call(V),O&&this.vbar.on(".drag",null).call(V)}this.setTranslate(e,r)},l.prototype.disable=function(){(this.hbar||this.vbar)&&(this.bg.attr({width:0,height:0}),this.container.on("wheel",null).on(".drag",null).call(i.setClipUrl,null),delete this._clipRect),this.hbar&&(this.hbar.on(".drag",null),this.hbar.remove(),delete this.hbar,delete this._hbarXMin,delete this._hbarTranslateMax),this.vbar&&(this.vbar.on(".drag",null),this.vbar.remove(),delete this.vbar,delete this._vbarYMin,delete this._vbarTranslateMax)},l.prototype._onBoxDrag=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t-=n.event.dx),this.vbar&&(e-=n.event.dy),this.setTranslate(t,e)},l.prototype._onBoxWheel=function(){var t=this.translateX,e=this.translateY;this.hbar&&(t+=n.event.deltaY),this.vbar&&(e+=n.event.deltaY),this.setTranslate(t,e)},l.prototype._onBarDrag=function(){var t=this.translateX,e=this.translateY;if(this.hbar){var r=t+this._hbarXMin,a=r+this._hbarTranslateMax;t=(o.constrain(n.event.x,r,a)-r)/(a-r)*(this.position.w-this._box.w)}if(this.vbar){var i=e+this._vbarYMin,l=i+this._vbarTranslateMax;e=(o.constrain(n.event.y,i,l)-i)/(l-i)*(this.position.h-this._box.h)}this.setTranslate(t,e)},l.prototype.setTranslate=function(t,e){var r=this.position.w-this._box.w,n=this.position.h-this._box.h;if(t=o.constrain(t||0,0,r),e=o.constrain(e||0,0,n),this.translateX=t,this.translateY=e,this.container.call(i.setTranslate,this._box.l-this.position.l-t,this._box.t-this.position.t-e),this._clipRect&&this._clipRect.attr({x:Math.floor(this.position.l+t-.5),y:Math.floor(this.position.t+e-.5)}),this.hbar){var a=t/r;this.hbar.call(i.setTranslate,t+a*this._hbarTranslateMax,e)}if(this.vbar){var l=e/n;this.vbar.call(i.setTranslate,t,e+l*this._vbarTranslateMax)}}},{"../../lib":163,"../color":45,"../drawing":70,d3:10}],143:[function(t,e,r){"use strict";e.exports={FROM_BL:{left:0,center:.5,right:1,bottom:0,middle:.5,top:1},FROM_TL:{left:0,center:.5,right:1,bottom:1,middle:.5,top:0},FROM_BR:{left:1,center:.5,right:0,bottom:0,middle:.5,top:1},LINE_SPACING:1.3,MID_SHIFT:.35,OPPOSITE_SIDE:{left:"right",right:"left",top:"bottom",bottom:"top"}}},{}],144:[function(t,e,r){"use strict";e.exports={SHOW_PLACEHOLDER:100,HIDE_PLACEHOLDER:1e3,DBLCLICKDELAY:300,DESELECTDIM:.2}},{}],145:[function(t,e,r){"use strict";e.exports={BADNUM:void 0,FP_SAFE:Number.MAX_VALUE/1e4,ONEAVGYEAR:315576e5,ONEAVGMONTH:26298e5,ONEDAY:864e5,ONEHOUR:36e5,ONEMIN:6e4,ONESEC:1e3,EPOCHJD:2440587.5,ALMOST_EQUAL:1-1e-6,MINUS_SIGN:"\u2212"}},{}],146:[function(t,e,r){"use strict";e.exports={entityToUnicode:{mu:"\u03bc","#956":"\u03bc",amp:"&","#28":"&",lt:"<","#60":"<",gt:">","#62":">",nbsp:"\xa0","#160":"\xa0",times:"\xd7","#215":"\xd7",plusmn:"\xb1","#177":"\xb1",deg:"\xb0","#176":"\xb0"}}},{}],147:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],148:[function(t,e,r){"use strict";r.version="1.39.2",t("es6-promise").polyfill(),t("../build/plotcss"),t("./fonts/mathjax_config");for(var n=t("./registry"),a=r.register=n.register,i=t("./plot_api"),o=Object.keys(i),l=0;l<o.length;l++){var s=o[l];r[s]=i[s],a({moduleType:"apiMethod",name:s,fn:i[s]})}a(t("./traces/scatter")),a([t("./components/fx"),t("./components/legend"),t("./components/annotations"),t("./components/annotations3d"),t("./components/shapes"),t("./components/images"),t("./components/updatemenus"),t("./components/sliders"),t("./components/rangeslider"),t("./components/rangeselector"),t("./components/grid"),t("./components/errorbars")]),a([t("./locale-en"),t("./locale-en-us")]),r.Icons=t("../build/ploticon"),r.Plots=t("./plots/plots"),r.Fx=t("./components/fx"),r.Snapshot=t("./snapshot"),r.PlotSchema=t("./plot_api/plot_schema"),r.Queue=t("./lib/queue"),r.d3=t("d3")},{"../build/plotcss":1,"../build/ploticon":2,"./components/annotations":38,"./components/annotations3d":43,"./components/errorbars":76,"./components/fx":87,"./components/grid":91,"./components/images":96,"./components/legend":105,"./components/rangeselector":116,"./components/rangeslider":122,"./components/shapes":130,"./components/sliders":135,"./components/updatemenus":141,"./fonts/mathjax_config":149,"./lib/queue":177,"./locale-en":188,"./locale-en-us":187,"./plot_api":192,"./plot_api/plot_schema":196,"./plots/plots":239,"./registry":247,"./snapshot":252,"./traces/scatter":325,d3:10,"es6-promise":11}],149:[function(t,e,r){"use strict";"undefined"!=typeof MathJax?(r.MathJax=!0,MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()):r.MathJax=!1},{}],150:[function(t,e,r){"use strict";var n=Math.PI;r.deg2rad=function(t){return t/180*n},r.rad2deg=function(t){return t/n*180},r.wrap360=function(t){var e=t%360;return e<0?e+360:e},r.wrap180=function(t){return Math.abs(t)>180&&(t-=360*Math.round(t/360)),t}},{}],151:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../constants/numerical").BADNUM,i=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;e.exports=function(t){return"string"==typeof t&&(t=t.replace(i,"")),n(t)?Number(t):a}},{"../constants/numerical":145,"fast-isnumeric":13}],152:[function(t,e,r){"use strict";e.exports=function(t){var e=t._fullLayout;e._glcanvas&&e._glcanvas.size()&&e._glcanvas.each(function(t){t.regl&&t.regl.clear({color:!0,depth:!0})})}},{}],153:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("tinycolor2"),i=t("../plots/attributes"),o=t("../components/colorscale/get_scale"),l=(Object.keys(t("../components/colorscale/scales")),t("./nested_property")),s=t("./regex").counter,c=t("../constants/interactions").DESELECTDIM,u=t("./angles").wrap180,f=t("./is_array").isArrayOrTypedArray;function d(t,e){var n=r.valObjectMeta[e.valType];if(e.arrayOk&&f(t))return!0;if(n.validateFunction)return n.validateFunction(t,e);var a={},i=a,o={set:function(t){i=t}};return n.coerceFunction(t,o,a,e),i!==a}r.valObjectMeta={data_array:{coerceFunction:function(t,e,r){f(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)},validateFunction:function(t,e){e.coerceNumber&&(t=+t);for(var r=e.values,n=0;n<r.length;n++){var a=String(r[n]);if("/"===a.charAt(0)&&"/"===a.charAt(a.length-1)){if(new RegExp(a.substr(1,a.length-2)).test(t))return!0}else if(t===r[n])return!0}return!1}},boolean:{coerceFunction:function(t,e,r){!0===t||!1===t?e.set(t):e.set(r)}},number:{coerceFunction:function(t,e,r,a){!n(t)||void 0!==a.min&&t<a.min||void 0!==a.max&&t>a.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,a){t%1||!n(t)||void 0!==a.min&&t<a.min||void 0!==a.max&&t>a.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if("string"!=typeof t){var a="number"==typeof t;!0!==n.strict&&a?e.set(String(t)):e.set(r)}else n.noBlank&&!t?e.set(r):e.set(t)}},color:{coerceFunction:function(t,e,r){a(t).isValid()?e.set(t):e.set(r)}},colorlist:{coerceFunction:function(t,e,r){Array.isArray(t)&&t.length&&t.every(function(t){return a(t).isValid()})?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?e.set(u(+t)):e.set(r)}},subplotid:{coerceFunction:function(t,e,r,n){var a=n.regex||s(r);"string"==typeof t&&a.test(t)?e.set(t):e.set(r)},validateFunction:function(t,e){var r=e.dflt;return t===r||"string"==typeof t&&!!s(r).test(t)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"==typeof t)if(-1===(n.extras||[]).indexOf(t)){for(var a=t.split("+"),i=0;i<a.length;){var o=a[i];-1===n.flags.indexOf(o)||a.indexOf(o)<i?a.splice(i,1):i++}a.length?e.set(a.join("+")):e.set(r)}else e.set(t);else e.set(r)}},any:{coerceFunction:function(t,e,r){void 0===t?e.set(r):e.set(t)}},info_array:{coerceFunction:function(t,e,n,a){function i(t,e,n){var a,i={set:function(t){a=t}};return void 0===n&&(n=e.dflt),r.valObjectMeta[e.valType].coerceFunction(t,i,n,e),a}var o=2===a.dimensions||"1-2"===a.dimensions&&Array.isArray(t)&&Array.isArray(t[0]);if(Array.isArray(t)){var l,s,c,u,f,d,p=a.items,h=[],g=Array.isArray(p),y=g&&o&&Array.isArray(p[0]),v=o&&g&&!y,m=g&&!v?p.length:t.length;if(n=Array.isArray(n)?n:[],o)for(l=0;l<m;l++)for(h[l]=[],c=Array.isArray(t[l])?t[l]:[],f=v?p.length:g?p[l].length:c.length,s=0;s<f;s++)u=v?p[s]:g?p[l][s]:p,void 0!==(d=i(c[s],u,(n[l]||[])[s]))&&(h[l][s]=d);else for(l=0;l<m;l++)void 0!==(d=i(t[l],g?p[l]:p,n[l]))&&(h[l]=d);e.set(h)}else e.set(n)},validateFunction:function(t,e){if(!Array.isArray(t))return!1;var r=e.items,n=Array.isArray(r),a=2===e.dimensions;if(!e.freeLength&&t.length!==r.length)return!1;for(var i=0;i<t.length;i++)if(a){if(!Array.isArray(t[i])||!e.freeLength&&t[i].length!==r[i].length)return!1;for(var o=0;o<t[i].length;o++)if(!d(t[i][o],n?r[i][o]:r))return!1}else if(!d(t[i],n?r[i]:r))return!1;return!0}}},r.coerce=function(t,e,n,a,i){var o=l(n,a).get(),s=l(t,a),c=l(e,a),u=s.get(),p=e._template;if(void 0===u&&p&&(u=l(p,a).get(),p=0),void 0===i&&(i=o.dflt),o.arrayOk&&f(u))return c.set(u),u;var h=r.valObjectMeta[o.valType].coerceFunction;h(u,c,i,o);var g=c.get();return p&&g===i&&!d(u,o)&&(h(u=l(p,a).get(),c,i,o),g=c.get()),g},r.coerce2=function(t,e,n,a,i){var o=l(t,a),s=r.coerce(t,e,n,a,i),c=o.get();return null!=c&&s},r.coerceFont=function(t,e,r){var n={};return r=r||{},n.family=t(e+".family",r.family),n.size=t(e+".size",r.size),n.color=t(e+".color",r.color),n},r.coerceHoverinfo=function(t,e,n){var a,o=e._module.attributes,l=o.hoverinfo?o:i,s=l.hoverinfo;if(1===n._dataLength){var c="all"===s.dflt?s.flags.slice():s.dflt.split("+");c.splice(c.indexOf("name"),1),a=c.join("+")}return r.coerce(t,e,l,"hoverinfo",a)},r.coerceSelectionMarkerOpacity=function(t,e){if(t.marker){var r,n,a=t.marker.opacity;if(void 0!==a)f(a)||t.selected||t.unselected||(r=a,n=c*a),e("selected.marker.opacity",r),e("unselected.marker.opacity",n)}},r.validate=d},{"../components/colorscale/get_scale":58,"../components/colorscale/scales":64,"../constants/interactions":144,"../plots/attributes":204,"./angles":150,"./is_array":164,"./nested_property":171,"./regex":178,"fast-isnumeric":13,tinycolor2:28}],154:[function(t,e,r){"use strict";var n,a,i=t("d3"),o=t("fast-isnumeric"),l=t("./loggers"),s=t("./mod"),c=t("../constants/numerical"),u=c.BADNUM,f=c.ONEDAY,d=c.ONEHOUR,p=c.ONEMIN,h=c.ONESEC,g=c.EPOCHJD,y=t("../registry"),v=i.time.format.utc,m=/^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m,x=/^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m,b=(new Date).getFullYear()-70;function _(t){return t&&y.componentsRegistry.calendars&&"string"==typeof t&&"gregorian"!==t}function w(t,e){return String(t+Math.pow(10,e)).substr(1)}r.dateTick0=function(t,e){return _(t)?e?y.getComponentMethod("calendars","CANONICAL_SUNDAY")[t]:y.getComponentMethod("calendars","CANONICAL_TICK")[t]:e?"2000-01-02":"2000-01-01"},r.dfltRange=function(t){return _(t)?y.getComponentMethod("calendars","DFLTRANGE")[t]:["2000-01-01","2001-01-01"]},r.isJSDate=function(t){return"object"==typeof t&&null!==t&&"function"==typeof t.getTime},r.dateTime2ms=function(t,e){if(r.isJSDate(t)){var i=t.getTimezoneOffset()*p,o=(t.getUTCMinutes()-t.getMinutes())*p+(t.getUTCSeconds()-t.getSeconds())*h+(t.getUTCMilliseconds()-t.getMilliseconds());if(o){var l=3*p;i=i-l/2+s(o-i+l/2,l)}return(t=Number(t)-i)>=n&&t<=a?t:u}if("string"!=typeof t&&"number"!=typeof t)return u;t=String(t);var c=_(e),v=t.charAt(0);!c||"G"!==v&&"g"!==v||(t=t.substr(1),e="");var w=c&&"chinese"===e.substr(0,7),k=t.match(w?x:m);if(!k)return u;var M=k[1],T=k[3]||"1",A=Number(k[5]||1),L=Number(k[7]||0),C=Number(k[9]||0),S=Number(k[11]||0);if(c){if(2===M.length)return u;var O;M=Number(M);try{var P=y.getComponentMethod("calendars","getCal")(e);if(w){var D="i"===T.charAt(T.length-1);T=parseInt(T,10),O=P.newDate(M,P.toMonthIndex(M,T,D),A)}else O=P.newDate(M,Number(T),A)}catch(t){return u}return O?(O.toJD()-g)*f+L*d+C*p+S*h:u}M=2===M.length?(Number(M)+2e3-b)%100+b:Number(M),T-=1;var z=new Date(Date.UTC(2e3,T,A,L,C));return z.setUTCFullYear(M),z.getUTCMonth()!==T?u:z.getUTCDate()!==A?u:z.getTime()+S*h},n=r.MIN_MS=r.dateTime2ms("-9999"),a=r.MAX_MS=r.dateTime2ms("9999-12-31 23:59:59.9999"),r.isDateTime=function(t,e){return r.dateTime2ms(t,e)!==u};var k=90*f,M=3*d,T=5*p;function A(t,e,r,n,a){if((e||r||n||a)&&(t+=" "+w(e,2)+":"+w(r,2),(n||a)&&(t+=":"+w(n,2),a))){for(var i=4;a%10==0;)i-=1,a/=10;t+="."+w(a,i)}return t}r.ms2DateTime=function(t,e,r){if("number"!=typeof t||!(t>=n&&t<=a))return u;e||(e=0);var i,o,l,c,m,x,b=Math.floor(10*s(t+.05,1)),w=Math.round(t-b/10);if(_(r)){var L=Math.floor(w/f)+g,C=Math.floor(s(t,f));try{i=y.getComponentMethod("calendars","getCal")(r).fromJD(L).formatDate("yyyy-mm-dd")}catch(t){i=v("G%Y-%m-%d")(new Date(w))}if("-"===i.charAt(0))for(;i.length<11;)i="-0"+i.substr(1);else for(;i.length<10;)i="0"+i;o=e<k?Math.floor(C/d):0,l=e<k?Math.floor(C%d/p):0,c=e<M?Math.floor(C%p/h):0,m=e<T?C%h*10+b:0}else x=new Date(w),i=v("%Y-%m-%d")(x),o=e<k?x.getUTCHours():0,l=e<k?x.getUTCMinutes():0,c=e<M?x.getUTCSeconds():0,m=e<T?10*x.getUTCMilliseconds()+b:0;return A(i,o,l,c,m)},r.ms2DateTimeLocal=function(t){if(!(t>=n+f&&t<=a-f))return u;var e=Math.floor(10*s(t+.05,1)),r=new Date(Math.round(t-e/10));return A(i.time.format("%Y-%m-%d")(r),r.getHours(),r.getMinutes(),r.getSeconds(),10*r.getUTCMilliseconds()+e)},r.cleanDate=function(t,e,n){if(r.isJSDate(t)||"number"==typeof t){if(_(n))return l.error("JS Dates and milliseconds are incompatible with world calendars",t),e;if(!(t=r.ms2DateTimeLocal(+t))&&void 0!==e)return e}else if(!r.isDateTime(t,n))return l.error("unrecognized date",t),e;return t};var L=/%\d?f/g;function C(t,e,r,n){t=t.replace(L,function(t){var r=Math.min(+t.charAt(1)||6,6);return(e/1e3%1+2).toFixed(r).substr(2).replace(/0+$/,"")||"0"});var a=new Date(Math.floor(e+.05));if(_(n))try{t=y.getComponentMethod("calendars","worldCalFmt")(t,e,n)}catch(t){return"Invalid"}return r(t)(a)}var S=[59,59.9,59.99,59.999,59.9999];r.formatDate=function(t,e,r,n,a,i){if(a=_(a)&&a,!e)if("y"===r)e=i.year;else if("m"===r)e=i.month;else{if("d"!==r)return function(t,e){var r=s(t+.05,f),n=w(Math.floor(r/d),2)+":"+w(s(Math.floor(r/p),60),2);if("M"!==e){o(e)||(e=0);var a=(100+Math.min(s(t/h,60),S[e])).toFixed(e).substr(1);e>0&&(a=a.replace(/0+$/,"").replace(/[\.]$/,"")),n+=":"+a}return n}(t,r)+"\n"+C(i.dayMonthYear,t,n,a);e=i.dayMonth+"\n"+i.year}return C(e,t,n,a)};var O=3*f;r.incrementMonth=function(t,e,r){r=_(r)&&r;var n=s(t,f);if(t=Math.round(t-n),r)try{var a=Math.round(t/f)+g,i=y.getComponentMethod("calendars","getCal")(r),o=i.fromJD(a);return e%12?i.add(o,e,"m"):i.add(o,e/12,"y"),(o.toJD()-g)*f+n}catch(e){l.error("invalid ms "+t+" in calendar "+r)}var c=new Date(t+O);return c.setUTCMonth(c.getUTCMonth()+e)+n-O},r.findExactDates=function(t,e){for(var r,n,a=0,i=0,l=0,s=0,c=_(e)&&y.getComponentMethod("calendars","getCal")(e),u=0;u<t.length;u++)if(n=t[u],o(n)){if(!(n%f))if(c)try{1===(r=c.fromJD(n/f+g)).day()?1===r.month()?a++:i++:l++}catch(t){}else 1===(r=new Date(n)).getUTCDate()?0===r.getUTCMonth()?a++:i++:l++}else s++;l+=i+=a;var d=t.length-s;return{exactYears:a/d,exactMonths:i/d,exactDays:l/d}}},{"../constants/numerical":145,"../registry":247,"./loggers":168,"./mod":170,d3:10,"fast-isnumeric":13}],155:[function(t,e,r){"use strict";e.exports=function(t,e){return Array.isArray(t)||(t=[]),t.length=e,t}},{}],156:[function(t,e,r){"use strict";var n=t("events").EventEmitter,a={init:function(t){if(t._ev instanceof n)return t;var e=new n,r=new n;return t._ev=e,t._internalEv=r,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t._internalOn=r.on.bind(r),t._internalOnce=r.once.bind(r),t._removeInternalListener=r.removeListener.bind(r),t._removeAllInternalListeners=r.removeAllListeners.bind(r),t.emit=function(n,a){"undefined"!=typeof jQuery&&jQuery(t).trigger(n,a),e.emit(n,a),r.emit(n,a)},t},triggerHandler:function(t,e,r){var n,a;"undefined"!=typeof jQuery&&(n=jQuery(t).triggerHandler(e,r));var i=t._ev;if(!i)return n;var o,l=i._events[e];if(!l)return n;function s(t){return t.listener?(i.removeListener(e,t.listener),t.fired?void 0:(t.fired=!0,t.listener.apply(i,[r]))):t.apply(i,[r])}for(l=Array.isArray(l)?l:[l],o=0;o<l.length-1;o++)s(l[o]);return a=s(l[o]),void 0!==n?n:a},purge:function(t){return delete t._ev,delete t.on,delete t.once,delete t.removeListener,delete t.removeAllListeners,delete t.emit,delete t._ev,delete t._internalEv,delete t._internalOn,delete t._internalOnce,delete t._removeInternalListener,delete t._removeAllInternalListeners,t}};e.exports=a},{events:12}],157:[function(t,e,r){"use strict";var n=t("./is_plain_object.js"),a=Array.isArray;function i(t,e,r,o){var l,s,c,u,f,d,p=t[0],h=t.length;if(2===h&&a(p)&&a(t[1])&&0===p.length){if(function(t,e){var r,n;for(r=0;r<t.length;r++){if(null!==(n=t[r])&&"object"==typeof n)return!1;void 0!==n&&(e[r]=n)}return!0}(t[1],p))return p;p.splice(0,p.length)}for(var g=1;g<h;g++)for(s in l=t[g])c=p[s],u=l[s],o&&a(u)?p[s]=u:e&&u&&(n(u)||(f=a(u)))?(f?(f=!1,d=c&&a(c)?c:[]):d=c&&n(c)?c:{},p[s]=i([d,u],e,r,o)):("undefined"!=typeof u||r)&&(p[s]=u);return p}r.extendFlat=function(){return i(arguments,!1,!1,!1)},r.extendDeep=function(){return i(arguments,!0,!1,!1)},r.extendDeepAll=function(){return i(arguments,!0,!0,!1)},r.extendDeepNoArrays=function(){return i(arguments,!0,!1,!0)}},{"./is_plain_object.js":165}],158:[function(t,e,r){"use strict";e.exports=function(t){for(var e={},r=[],n=0,a=0;a<t.length;a++){var i=t[a];1!==e[i]&&(e[i]=1,r[n++]=i)}return r}},{}],159:[function(t,e,r){"use strict";function n(t){return!0===t.visible}function a(t){return!0===t[0].trace.visible}e.exports=function(t){for(var e,r=(e=t,Array.isArray(e)&&Array.isArray(e[0])&&e[0][0]&&e[0][0].trace?a:n),i=[],o=0;o<t.length;o++){var l=t[o];r(l)&&i.push(l)}return i}},{}],160:[function(t,e,r){"use strict";var n,a,i,o=t("./mod");function l(t,e,r,n,a,i,o,l){var s=r-t,c=a-t,u=o-a,f=n-e,d=i-e,p=l-i,h=s*p-u*f;if(0===h)return null;var g=(c*p-u*d)/h,y=(c*f-s*d)/h;return y<0||y>1||g<0||g>1?null:{x:t+s*g,y:e+f*g}}function s(t,e,r,n,a){var i=n*t+a*e;if(i<0)return n*n+a*a;if(i>r){var o=n-t,l=a-e;return o*o+l*l}var s=n*e-a*t;return s*s/r}r.segmentsIntersect=l,r.segmentDistance=function(t,e,r,n,a,i,o,c){if(l(t,e,r,n,a,i,o,c))return 0;var u=r-t,f=n-e,d=o-a,p=c-i,h=u*u+f*f,g=d*d+p*p,y=Math.min(s(u,f,h,a-t,i-e),s(u,f,h,o-t,c-e),s(d,p,g,t-a,e-i),s(d,p,g,r-a,n-i));return Math.sqrt(y)},r.getTextLocation=function(t,e,r,l){if(t===a&&l===i||(n={},a=t,i=l),n[r])return n[r];var s=t.getPointAtLength(o(r-l/2,e)),c=t.getPointAtLength(o(r+l/2,e)),u=Math.atan((c.y-s.y)/(c.x-s.x)),f=t.getPointAtLength(o(r,e)),d={x:(4*f.x+s.x+c.x)/6,y:(4*f.y+s.y+c.y)/6,theta:u};return n[r]=d,d},r.clearLocationCache=function(){a=null},r.getVisibleSegment=function(t,e,r){var n,a,i=e.left,o=e.right,l=e.top,s=e.bottom,c=0,u=t.getTotalLength(),f=u;function d(e){var r=t.getPointAtLength(e);0===e?n=r:e===u&&(a=r);var c=r.x<i?i-r.x:r.x>o?r.x-o:0,f=r.y<l?l-r.y:r.y>s?r.y-s:0;return Math.sqrt(c*c+f*f)}for(var p=d(c);p;){if((c+=p+r)>f)return;p=d(c)}for(p=d(f);p;){if(c>(f-=p+r))return;p=d(f)}return{min:c,max:f,len:f-c,total:u,isClosed:0===c&&f===u&&Math.abs(n.x-a.x)<.1&&Math.abs(n.y-a.y)<.1}},r.findPointOnPath=function(t,e,r,n){for(var a,i,o,l=(n=n||{}).pathLength||t.getTotalLength(),s=n.tolerance||.001,c=n.iterationLimit||30,u=t.getPointAtLength(0)[r]>t.getPointAtLength(l)[r]?-1:1,f=0,d=0,p=l;f<c;){if(a=(d+p)/2,o=(i=t.getPointAtLength(a))[r]-e,Math.abs(o)<s)return i;u*o>0?p=a:d=a,f++}return i}},{"./mod":170}],161:[function(t,e,r){"use strict";e.exports=function(t){var e;if("string"==typeof t){if(null===(e=document.getElementById(t)))throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null==t)throw new Error("DOM element provided is null or undefined");return t}},{}],162:[function(t,e,r){"use strict";e.exports=function(t){return t}},{}],163:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../constants/numerical"),o=i.FP_SAFE,l=i.BADNUM,s=e.exports={};s.nestedProperty=t("./nested_property"),s.keyedContainer=t("./keyed_container"),s.relativeAttr=t("./relative_attr"),s.isPlainObject=t("./is_plain_object"),s.mod=t("./mod"),s.toLogRange=t("./to_log_range"),s.relinkPrivateKeys=t("./relink_private"),s.ensureArray=t("./ensure_array");var c=t("./is_array");s.isTypedArray=c.isTypedArray,s.isArrayOrTypedArray=c.isArrayOrTypedArray,s.isArray1D=c.isArray1D;var u=t("./coerce");s.valObjectMeta=u.valObjectMeta,s.coerce=u.coerce,s.coerce2=u.coerce2,s.coerceFont=u.coerceFont,s.coerceHoverinfo=u.coerceHoverinfo,s.coerceSelectionMarkerOpacity=u.coerceSelectionMarkerOpacity,s.validate=u.validate;var f=t("./dates");s.dateTime2ms=f.dateTime2ms,s.isDateTime=f.isDateTime,s.ms2DateTime=f.ms2DateTime,s.ms2DateTimeLocal=f.ms2DateTimeLocal,s.cleanDate=f.cleanDate,s.isJSDate=f.isJSDate,s.formatDate=f.formatDate,s.incrementMonth=f.incrementMonth,s.dateTick0=f.dateTick0,s.dfltRange=f.dfltRange,s.findExactDates=f.findExactDates,s.MIN_MS=f.MIN_MS,s.MAX_MS=f.MAX_MS;var d=t("./search");s.findBin=d.findBin,s.sorterAsc=d.sorterAsc,s.sorterDes=d.sorterDes,s.distinctVals=d.distinctVals,s.roundUp=d.roundUp;var p=t("./stats");s.aggNums=p.aggNums,s.len=p.len,s.mean=p.mean,s.midRange=p.midRange,s.variance=p.variance,s.stdev=p.stdev,s.interp=p.interp;var h=t("./matrix");s.init2dArray=h.init2dArray,s.transposeRagged=h.transposeRagged,s.dot=h.dot,s.translationMatrix=h.translationMatrix,s.rotationMatrix=h.rotationMatrix,s.rotationXYMatrix=h.rotationXYMatrix,s.apply2DTransform=h.apply2DTransform,s.apply2DTransform2=h.apply2DTransform2;var g=t("./angles");s.deg2rad=g.deg2rad,s.rad2deg=g.rad2deg,s.wrap360=g.wrap360,s.wrap180=g.wrap180;var y=t("./geometry2d");s.segmentsIntersect=y.segmentsIntersect,s.segmentDistance=y.segmentDistance,s.getTextLocation=y.getTextLocation,s.clearLocationCache=y.clearLocationCache,s.getVisibleSegment=y.getVisibleSegment,s.findPointOnPath=y.findPointOnPath;var v=t("./extend");s.extendFlat=v.extendFlat,s.extendDeep=v.extendDeep,s.extendDeepAll=v.extendDeepAll,s.extendDeepNoArrays=v.extendDeepNoArrays;var m=t("./loggers");s.log=m.log,s.warn=m.warn,s.error=m.error;var x=t("./regex");s.counterRegex=x.counter;var b=t("./throttle");function _(t){var e={};for(var r in t)for(var n=t[r],a=0;a<n.length;a++)e[n[a]]=+r;return e}s.throttle=b.throttle,s.throttleDone=b.done,s.clearThrottle=b.clear,s.getGraphDiv=t("./get_graph_div"),s._=t("./localize"),s.notifier=t("./notifier"),s.filterUnique=t("./filter_unique"),s.filterVisible=t("./filter_visible"),s.pushUnique=t("./push_unique"),s.cleanNumber=t("./clean_number"),s.ensureNumber=function(t){return a(t)?(t=Number(t))<-o||t>o?l:a(t)?Number(t):l:l},s.isIndex=function(t,e){return!(void 0!==e&&t>=e)&&(a(t)&&t>=0&&t%1==0)},s.noop=t("./noop"),s.identity=t("./identity"),s.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;a<e.length;a++){var i=e[a],o=s.nestedProperty(t,i.replace("?",r)),l=s.nestedProperty(t,i.replace("?",n)),c=o.get();o.set(l.get()),l.set(c)}},s.raiseToTop=function(t){t.parentNode.appendChild(t)},s.cancelTransition=function(t){return t.transition().duration(0)},s.constrain=function(t,e,r){return e>r?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},s.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},s.simpleMap=function(t,e,r,n){for(var a=t.length,i=new Array(a),o=0;o<a;o++)i[o]=e(t[o],r,n);return i},s.randstr=function t(e,r,n,a){if(n||(n=16),void 0===r&&(r=24),r<=0)return"0";var i,o,l=Math.log(Math.pow(2,r))/Math.log(n),c="";for(i=2;l===1/0;i*=2)l=Math.log(Math.pow(2,r/i))/Math.log(n)*i;var u=l-Math.floor(l);for(i=0;i<Math.floor(l);i++)c=Math.floor(Math.random()*n).toString(n)+c;u&&(o=Math.pow(n,u),c=Math.floor(Math.random()*o).toString(n)+c);var f=parseInt(c,n);return e&&e[c]||f!==1/0&&f>=Math.pow(2,r)?a>10?(s.warn("randstr failed uniqueness"),c):t(e,r,n,(a||0)+1):c},s.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={optionList:[],_newoption:function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)}};return r["_"+e]=t,r},s.smooth=function(t,e){if((e=Math.round(e)||0)<2)return t;var r,n,a,i,o=t.length,l=2*o,s=2*e-1,c=new Array(s),u=new Array(o);for(r=0;r<s;r++)c[r]=(1-Math.cos(Math.PI*(r+1)/e))/(2*e);for(r=0;r<o;r++){for(i=0,n=0;n<s;n++)(a=r+n+1-e)<-o?a-=l*Math.round(a/l):a>=l&&(a-=l*Math.floor(a/l)),a<0?a=-1-a:a>=o&&(a=l-1-a),i+=t[a]*c[n];u[r]=i}return u},s.syncOrAsync=function(t,e,r){var n;function a(){return s.syncOrAsync(t,e,r)}for(;t.length;)if((n=(0,t.splice(0,1)[0])(e))&&n.then)return n.then(a).then(void 0,s.promiseError);return r&&r(e)},s.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},s.noneOrAll=function(t,e,r){if(t){var n,a=!1,i=!0;for(n=0;n<r.length;n++)null!=t[r[n]]?a=!0:i=!1;if(a&&!i)for(n=0;n<r.length;n++)t[r[n]]=e[r[n]]}},s.mergeArray=function(t,e,r){if(s.isArrayOrTypedArray(t))for(var n=Math.min(t.length,e.length),a=0;a<n;a++)e[a][r]=t[a]},s.fillArray=function(t,e,r,n){if(n=n||s.identity,s.isArrayOrTypedArray(t))for(var a=0;a<e.length;a++)e[a][r]=n(t[a])},s.castOption=function(t,e,r,n){n=n||s.identity;var a=s.nestedProperty(t,r).get();return s.isArrayOrTypedArray(a)?Array.isArray(e)&&s.isArrayOrTypedArray(a[e[0]])?n(a[e[0]][e[1]]):n(a[e]):a},s.extractOption=function(t,e,r,n){if(r in t)return t[r];var a=s.nestedProperty(e,n).get();return Array.isArray(a)?void 0:a},s.tagSelected=function(t,e,r){var n,a,i=e.selectedpoints,o=e._indexToPoints;o&&(n=_(o));for(var l=0;l<i.length;l++){var c=i[l];if(s.isIndex(c)){var u=n?n[c]:c,f=r?r[u]:u;void 0!==(a=f)&&a<t.length&&(t[f].selected=1)}}},s.selIndices2selPoints=function(t){var e=t.selectedpoints,r=t._indexToPoints;if(r){for(var n=_(r),a=[],i=0;i<e.length;i++){var o=e[i];if(s.isIndex(o)){var l=n[o];s.isIndex(l)&&a.push(l)}}return a}return e},s.getTargetArray=function(t,e){var r=e.target;if("string"==typeof r&&r){var n=s.nestedProperty(t,r).get();return!!Array.isArray(n)&&n}return!!Array.isArray(r)&&r},s.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,i,o=Object.keys(t);for(n=0;n<o.length;n++)i=t[a=o[n]],"_"!==a.charAt(0)&&"function"!=typeof i&&("module"===a?r[a]=i:Array.isArray(i)?r[a]=i.slice(0,3):r[a]=i&&"object"==typeof i?s.minExtend(t[a],e[a]):i);for(o=Object.keys(e),n=0;n<o.length;n++)"object"==typeof(i=e[a=o[n]])&&a in r&&"object"==typeof r[a]||(r[a]=i);return r},s.titleCase=function(t){return t.charAt(0).toUpperCase()+t.substr(1)},s.containsAny=function(t,e){for(var r=0;r<e.length;r++)if(-1!==t.indexOf(e[r]))return!0;return!1},s.isPlotDiv=function(t){var e=n.select(t);return e.node()instanceof HTMLElement&&e.size()&&e.classed("js-plotly-plot")},s.removeElement=function(t){var e=t&&t.parentNode;e&&e.removeChild(t)},s.addStyleRule=function(t,e){if(!s.styleSheet){var r=document.createElement("style");r.appendChild(document.createTextNode("")),document.head.appendChild(r),s.styleSheet=r.sheet}var n=s.styleSheet;n.insertRule?n.insertRule(t+"{"+e+"}",0):n.addRule?n.addRule(t,e,0):s.warn("addStyleRule failed")},s.isIE=function(){return"undefined"!=typeof window.navigator.msSaveBlob},s.isD3Selection=function(t){return t&&"function"==typeof t.classed},s.ensureSingle=function(t,e,r,n){var a=t.select(e+(r?"."+r:""));if(a.size())return a;var i=t.append(e).classed(r,!0);return n&&i.call(n),i},s.ensureSingleById=function(t,e,r,n){var a=t.select(e+"#"+r);if(a.size())return a;var i=t.append(e).attr("id",r);return n&&i.call(n),i},s.objectFromPath=function(t,e){for(var r,n=t.split("."),a=r={},i=0;i<n.length;i++){var o=n[i],l=null,s=n[i].match(/(.*)\[([0-9]+)\]/);s?(o=s[1],l=s[2],r=r[o]=[],i===n.length-1?r[l]=e:r[l]={},r=r[l]):(i===n.length-1?r[o]=e:r[o]={},r=r[o])}return a};var w=/^([^\[\.]+)\.(.+)?/,k=/^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;s.expandObjectPaths=function(t){var e,r,n,a,i,o,l;if("object"==typeof t&&!Array.isArray(t))for(r in t)t.hasOwnProperty(r)&&((e=r.match(w))?(a=t[r],n=e[1],delete t[r],t[n]=s.extendDeepNoArrays(t[n]||{},s.objectFromPath(r,s.expandObjectPaths(a))[n])):(e=r.match(k))?(a=t[r],n=e[1],i=parseInt(e[2]),delete t[r],t[n]=t[n]||[],"."===e[3]?(l=e[4],o=t[n][i]=t[n][i]||{},s.extendDeepNoArrays(o,s.objectFromPath(l,s.expandObjectPaths(a)))):t[n][i]=s.expandObjectPaths(a)):t[r]=s.expandObjectPaths(t[r]));return t},s.numSeparate=function(t,e,r){if(r||(r=!1),"string"!=typeof e||0===e.length)throw new Error("Separator string required for formatting!");"number"==typeof t&&(t=String(t));var n=/(\d+)(\d{3})/,a=e.charAt(0),i=e.charAt(1),o=t.split("."),l=o[0],s=o.length>1?a+o[1]:"";if(i&&(o.length>1||l.length>4||r))for(;n.test(l);)l=l.replace(n,"$1"+i+"$2");return l+s};var M=/%{([^\s%{}]*)}/g,T=/^\w*$/;s.templateString=function(t,e){var r={};return t.replace(M,function(t,n){return T.test(n)?e[n]||"":(r[n]=r[n]||s.nestedProperty(e,n).get,r[n]()||"")})};s.subplotSort=function(t,e){for(var r=Math.min(t.length,e.length)+1,n=0,a=0,i=0;i<r;i++){var o=t.charCodeAt(i)||0,l=e.charCodeAt(i)||0,s=o>=48&&o<=57,c=l>=48&&l<=57;if(s&&(n=10*n+o-48),c&&(a=10*a+l-48),!s||!c){if(n!==a)return n-a;if(o!==l)return o-l}}return a-n};var A=2e9;s.seedPseudoRandom=function(){A=2e9},s.pseudoRandom=function(){var t=A;return A=(69069*A+1)%4294967296,Math.abs(A-t)<429496729?s.pseudoRandom():A/4294967296}},{"../constants/numerical":145,"./angles":150,"./clean_number":151,"./coerce":153,"./dates":154,"./ensure_array":155,"./extend":157,"./filter_unique":158,"./filter_visible":159,"./geometry2d":160,"./get_graph_div":161,"./identity":162,"./is_array":164,"./is_plain_object":165,"./keyed_container":166,"./localize":167,"./loggers":168,"./matrix":169,"./mod":170,"./nested_property":171,"./noop":172,"./notifier":173,"./push_unique":176,"./regex":178,"./relative_attr":179,"./relink_private":180,"./search":181,"./stats":183,"./throttle":185,"./to_log_range":186,d3:10,"fast-isnumeric":13}],164:[function(t,e,r){"use strict";var n="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer:{isView:function(){return!1}},a="undefined"==typeof DataView?function(){}:DataView;function i(t){return n.isView(t)&&!(t instanceof a)}function o(t){return Array.isArray(t)||i(t)}e.exports={isTypedArray:i,isArrayOrTypedArray:o,isArray1D:function(t){return!o(t[0])}}},{}],165:[function(t,e,r){"use strict";e.exports=function(t){return window&&window.process&&window.process.versions?"[object Object]"===Object.prototype.toString.call(t):"[object Object]"===Object.prototype.toString.call(t)&&Object.getPrototypeOf(t)===Object.prototype}},{}],166:[function(t,e,r){"use strict";var n=t("./nested_property"),a=/^\w*$/;e.exports=function(t,e,r,i){var o,l,s;r=r||"name",i=i||"value";var c={};e&&e.length?(s=n(t,e),l=s.get()):l=t,e=e||"";var u={};if(l)for(o=0;o<l.length;o++)u[l[o][r]]=o;var f=a.test(i),d={set:function(t,e){var a=null===e?4:0;if(!l){if(!s||4===a)return;l=[],s.set(l)}var o=u[t];if(void 0===o){if(4===a)return;a|=3,o=l.length,u[t]=o}else e!==(f?l[o][i]:n(l[o],i).get())&&(a|=2);var p=l[o]=l[o]||{};return p[r]=t,f?p[i]=e:n(p,i).set(e),null!==e&&(a&=-5),c[o]=c[o]|a,d},get:function(t){if(l){var e=u[t];return void 0===e?void 0:f?l[e][i]:n(l[e],i).get()}},rename:function(t,e){var n=u[t];return void 0===n?d:(c[n]=1|c[n],u[e]=n,delete u[t],l[n][r]=e,d)},remove:function(t){var e=u[t];if(void 0===e)return d;var a=l[e];if(Object.keys(a).length>2)return c[e]=2|c[e],d.set(t,null);if(f){for(o=e;o<l.length;o++)c[o]=3|c[o];for(o=e;o<l.length;o++)u[l[o][r]]--;l.splice(e,1),delete u[t]}else n(a,i).set(null),c[e]=6|c[e];return d},constructUpdate:function(){for(var t,a,o={},s=Object.keys(c),u=0;u<s.length;u++)a=s[u],t=e+"["+a+"]",l[a]?(1&c[a]&&(o[t+"."+r]=l[a][r]),2&c[a]&&(o[t+"."+i]=f?4&c[a]?null:l[a][i]:4&c[a]?null:n(l[a],i).get())):o[t]=null;return o}};return d}},{"./nested_property":171}],167:[function(t,e,r){"use strict";var n=t("../registry");e.exports=function(t,e){for(var r=t._context.locale,a=0;a<2;a++){for(var i=t._context.locales,o=0;o<2;o++){var l=(i[r]||{}).dictionary;if(l){var s=l[e];if(s)return s}i=n.localeRegistry}var c=r.split("-")[0];if(c===r)break;r=c}return e}},{"../registry":247}],168:[function(t,e,r){"use strict";var n=t("../plot_api/plot_config"),a=e.exports={};function i(t,e){if(t.apply)t.apply(t,e);else for(var r=0;r<e.length;r++)t(e[r])}a.log=function(){if(n.logging>1){for(var t=["LOG:"],e=0;e<arguments.length;e++)t.push(arguments[e]);i(console.trace||console.log,t)}},a.warn=function(){if(n.logging>0){for(var t=["WARN:"],e=0;e<arguments.length;e++)t.push(arguments[e]);i(console.trace||console.log,t)}},a.error=function(){if(n.logging>0){for(var t=["ERROR:"],e=0;e<arguments.length;e++)t.push(arguments[e]);i(console.error,t)}}},{"../plot_api/plot_config":195}],169:[function(t,e,r){"use strict";r.init2dArray=function(t,e){for(var r=new Array(t),n=0;n<t;n++)r[n]=new Array(e);return r},r.transposeRagged=function(t){var e,r,n=0,a=t.length;for(e=0;e<a;e++)n=Math.max(n,t[e].length);var i=new Array(n);for(e=0;e<n;e++)for(i[e]=new Array(a),r=0;r<a;r++)i[e][r]=t[r][e];return i},r.dot=function(t,e){if(!t.length||!e.length||t.length!==e.length)return null;var n,a,i=t.length;if(t[0].length)for(n=new Array(i),a=0;a<i;a++)n[a]=r.dot(t[a],e);else if(e[0].length){var o=r.transposeRagged(e);for(n=new Array(o.length),a=0;a<o.length;a++)n[a]=r.dot(t,o[a])}else for(n=0,a=0;a<i;a++)n+=t[a]*e[a];return n},r.translationMatrix=function(t,e){return[[1,0,t],[0,1,e],[0,0,1]]},r.rotationMatrix=function(t){var e=t*Math.PI/180;return[[Math.cos(e),-Math.sin(e),0],[Math.sin(e),Math.cos(e),0],[0,0,1]]},r.rotationXYMatrix=function(t,e,n){return r.dot(r.dot(r.translationMatrix(e,n),r.rotationMatrix(t)),r.translationMatrix(-e,-n))},r.apply2DTransform=function(t){return function(){var e=arguments;3===e.length&&(e=e[0]);var n=1===arguments.length?e[0]:[e[0],e[1]];return r.dot(t,[n[0],n[1],1]).slice(0,2)}},r.apply2DTransform2=function(t){var e=r.apply2DTransform(t);return function(t){return e(t.slice(0,2)).concat(e(t.slice(2,4)))}}},{}],170:[function(t,e,r){"use strict";e.exports=function(t,e){var r=t%e;return r<0?r+e:r}},{}],171:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("./is_array").isArrayOrTypedArray;e.exports=function(t,e){if(n(e))e=String(e);else if("string"!=typeof e||"[-1]"===e.substr(e.length-4))throw"bad property string";for(var r,i,o,s=0,c=e.split(".");s<c.length;){if(r=String(c[s]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/)){if(r[1])c[s]=r[1];else{if(0!==s)throw"bad property string";c.splice(0,1)}for(i=r[2].substr(1,r[2].length-2).split("]["),o=0;o<i.length;o++)s++,c.splice(s,0,Number(i[o]))}s++}return"object"!=typeof t?function(t,e,r){return{set:function(){throw"bad container"},get:function(){},astr:e,parts:r,obj:t}}(t,e,c):{set:l(t,c,e),get:function t(e,r){return function(){var n,i,o,l,s,c=e;for(l=0;l<r.length-1;l++){if(-1===(n=r[l])){for(i=!0,o=[],s=0;s<c.length;s++)o[s]=t(c[s],r.slice(l+1))(),o[s]!==o[0]&&(i=!1);return i?o[0]:o}if("number"==typeof n&&!a(c))return;if("object"!=typeof(c=c[n])||null===c)return}if("object"==typeof c&&null!==c&&null!==(o=c[r[l]]))return o}}(t,c),astr:e,parts:c,obj:t}};var i=/(^|\.)args\[/;function o(t,e){return void 0===t||null===t&&!e.match(i)}function l(t,e,r){return function(n){var i,l,f=t,d="",p=[[t,d]],h=o(n,r);for(l=0;l<e.length-1;l++){if("number"==typeof(i=e[l])&&!a(f))throw"array index but container is not an array";if(-1===i){if(h=!c(f,e.slice(l+1),n,r))break;return}if(!u(f,i,e[l+1],h))break;if("object"!=typeof(f=f[i])||null===f)throw"container is not an object";d=s(d,i),p.push([f,d])}if(h){if(l===e.length-1&&(delete f[e[l]],Array.isArray(f)&&+e[l]==f.length-1))for(;f.length&&void 0===f[f.length-1];)f.pop()}else f[e[l]]=n}}function s(t,e){var r=e;return n(e)?r="["+e+"]":t&&(r="."+e),t+r}function c(t,e,r,n){var i,s=a(r),c=!0,f=r,d=n.replace("-1",0),p=!s&&o(r,d),h=e[0];for(i=0;i<t.length;i++)d=n.replace("-1",i),s&&(p=o(f=r[i%r.length],d)),p&&(c=!1),u(t,i,h,p)&&l(t[i],e,n.replace("-1",i))(f);return c}function u(t,e,r,n){if(void 0===t[e]){if(n)return!1;t[e]="number"==typeof r?[]:{}}return!0}},{"./is_array":164,"fast-isnumeric":13}],172:[function(t,e,r){"use strict";e.exports=function(){}},{}],173:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=[];e.exports=function(t,e){if(-1===i.indexOf(t)){i.push(t);var r=1e3;a(e)?r=e:"long"===e&&(r=3e3);var o=n.select("body").selectAll(".plotly-notifier").data([0]);o.enter().append("div").classed("plotly-notifier",!0),o.selectAll(".notifier-note").data(i).enter().append("div").classed("notifier-note",!0).style("opacity",0).each(function(t){var e=n.select(this);e.append("button").classed("notifier-close",!0).html("&times;").on("click",function(){e.transition().call(l)});for(var a=e.append("p"),i=t.split(/<br\s*\/?>/g),o=0;o<i.length;o++)o&&a.append("br"),a.append("span").text(i[o]);e.transition().duration(700).style("opacity",1).transition().delay(r).call(l)})}function l(t){t.duration(700).style("opacity",0).each("end",function(t){var e=i.indexOf(t);-1!==e&&i.splice(e,1),n.select(this).remove()})}}},{d3:10,"fast-isnumeric":13}],174:[function(t,e,r){"use strict";var n=t("./setcursor"),a="data-savedcursor";e.exports=function(t,e){var r=t.attr(a);if(e){if(!r){for(var i=(t.attr("class")||"").split(" "),o=0;o<i.length;o++){var l=i[o];0===l.indexOf("cursor-")&&t.attr(a,l.substr(7)).classed(l,!1)}t.attr(a)||t.attr(a,"!!")}n(t,e)}else r&&(t.attr(a,null),"!!"===r?n(t):n(t,r))}},{"./setcursor":182}],175:[function(t,e,r){"use strict";var n=t("./matrix").dot,a=t("../constants/numerical").BADNUM,i=e.exports={};i.tester=function(t){if(Array.isArray(t[0][0]))return i.multitester(t);var e,r=t.slice(),n=r[0][0],o=n,l=r[0][1],s=l;for(r.push(r[0]),e=1;e<r.length;e++)n=Math.min(n,r[e][0]),o=Math.max(o,r[e][0]),l=Math.min(l,r[e][1]),s=Math.max(s,r[e][1]);var c,u=!1;5===r.length&&(r[0][0]===r[1][0]?r[2][0]===r[3][0]&&r[0][1]===r[3][1]&&r[1][1]===r[2][1]&&(u=!0,c=function(t){return t[0]===r[0][0]}):r[0][1]===r[1][1]&&r[2][1]===r[3][1]&&r[0][0]===r[3][0]&&r[1][0]===r[2][0]&&(u=!0,c=function(t){return t[1]===r[0][1]}));var f=!0,d=r[0];for(e=1;e<r.length;e++)if(d[0]!==r[e][0]||d[1]!==r[e][1]){f=!1;break}return{xmin:n,xmax:o,ymin:l,ymax:s,pts:r,contains:u?function(t,e){var r=t[0],i=t[1];return!(r===a||r<n||r>o||i===a||i<l||i>s||e&&c(t))}:function(t,e){var i=t[0],c=t[1];if(i===a||i<n||i>o||c===a||c<l||c>s)return!1;var u,f,d,p,h,g=r.length,y=r[0][0],v=r[0][1],m=0;for(u=1;u<g;u++)if(f=y,d=v,y=r[u][0],v=r[u][1],!(i<(p=Math.min(f,y))||i>Math.max(f,y)||c>Math.max(d,v)))if(c<Math.min(d,v))i!==p&&m++;else{if(c===(h=y===f?c:d+(i-f)*(v-d)/(y-f)))return 1!==u||!e;c<=h&&i!==p&&m++}return m%2==1},isRect:u,degenerate:f}},i.multitester=function(t){for(var e=[],r=t[0][0][0],n=r,a=t[0][0][1],o=a,l=0;l<t.length;l++){var s=i.tester(t[l]);s.subtract=t[l].subtract,e.push(s),r=Math.min(r,s.xmin),n=Math.max(n,s.xmax),a=Math.min(a,s.ymin),o=Math.max(o,s.ymax)}return{xmin:r,xmax:n,ymin:a,ymax:o,pts:[],contains:function(t,r){for(var n=!1,a=0;a<e.length;a++)e[a].contains(t,r)&&(n=!1===e[a].subtract);return n},isRect:!1,degenerate:!1}};var o=i.isSegmentBent=function(t,e,r,a){var i,o,l,s=t[e],c=[t[r][0]-s[0],t[r][1]-s[1]],u=n(c,c),f=Math.sqrt(u),d=[-c[1]/f,c[0]/f];for(i=e+1;i<r;i++)if(o=[t[i][0]-s[0],t[i][1]-s[1]],(l=n(o,c))<0||l>u||Math.abs(n(o,d))>a)return!0;return!1};i.filter=function(t,e){var r=[t[0]],n=0,a=0;function i(i){t.push(i);var l=r.length,s=n;r.splice(a+1);for(var c=s+1;c<t.length;c++)(c===t.length-1||o(t,s,c+1,e))&&(r.push(t[c]),r.length<l-2&&(n=c,a=r.length-1),s=c)}t.length>1&&i(t.pop());return{addPt:i,raw:t,filtered:r}}},{"../constants/numerical":145,"./matrix":169}],176:[function(t,e,r){"use strict";e.exports=function(t,e){if(e instanceof RegExp){var r,n=e.toString();for(r=0;r<t.length;r++)if(t[r]instanceof RegExp&&t[r].toString()===n)return t;t.push(e)}else!e&&0!==e||-1!==t.indexOf(e)||t.push(e);return t}},{}],177:[function(t,e,r){"use strict";var n=t("../lib"),a=t("../plot_api/plot_config");var i={add:function(t,e,r,n,i){var o,l;t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},l=t.undoQueue.index,t.autoplay?t.undoQueue.inSequence||(t.autoplay=!1):(!t.undoQueue.sequence||t.undoQueue.beginSequence?(o={undo:{calls:[],args:[]},redo:{calls:[],args:[]}},t.undoQueue.queue.splice(l,t.undoQueue.queue.length-l,o),t.undoQueue.index+=1):o=t.undoQueue.queue[l-1],t.undoQueue.beginSequence=!1,o&&(o.undo.calls.unshift(e),o.undo.args.unshift(r),o.redo.calls.push(n),o.redo.args.push(i)),t.undoQueue.queue.length>a.queueLength&&(t.undoQueue.queue.shift(),t.undoQueue.index--))},startSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},stopSequence:function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},undo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.undo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r<e.undo.calls.length;r++)i.plotDo(t,e.undo.calls[r],e.undo.args[r]);t.undoQueue.inSequence=!1,t.autoplay=!1}},redo:function(t){var e,r;if(t.framework&&t.framework.isPolar)t.framework.redo();else if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index>=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r<e.redo.calls.length;r++)i.plotDo(t,e.redo.calls[r],e.redo.args[r]);t.undoQueue.inSequence=!1,t.autoplay=!1,t.undoQueue.index++}}};i.plotDo=function(t,e,r){t.autoplay=!0,r=function(t,e){for(var r,a=[],i=0;i<e.length;i++)r=e[i],a[i]=r===t?r:"object"==typeof r?Array.isArray(r)?n.extendDeep([],r):n.extendDeepAll({},r):r;return a}(t,r),e.apply(null,r)},e.exports=i},{"../lib":163,"../plot_api/plot_config":195}],178:[function(t,e,r){"use strict";r.counter=function(t,e,r){var n=(e||"")+(r?"":"$");return"xy"===t?new RegExp("^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?"+n):new RegExp("^"+t+"([2-9]|[1-9][0-9]+)?"+n)}},{}],179:[function(t,e,r){"use strict";var n=/^(.*)(\.[^\.\[\]]+|\[\d\])$/,a=/^[^\.\[\]]+$/;e.exports=function(t,e){for(;e;){var r=t.match(n);if(r)t=r[1];else{if(!t.match(a))throw new Error("bad relativeAttr call:"+[t,e]);t=""}if("^"!==e.charAt(0))break;e=e.slice(1)}return t&&"["!==e.charAt(0)?t+"."+e:t+e}},{}],180:[function(t,e,r){"use strict";var n=t("./is_array").isArrayOrTypedArray,a=t("./is_plain_object");e.exports=function t(e,r){for(var i in r){var o=r[i],l=e[i];if(l!==o)if("_"===i.charAt(0)||"function"==typeof o){if(i in e)continue;e[i]=o}else if(n(o)&&n(l)&&a(o[0])){if("customdata"===i||"ids"===i)continue;for(var s=Math.min(o.length,l.length),c=0;c<s;c++)l[c]!==o[c]&&a(o[c])&&a(l[c])&&t(l[c],o[c])}else a(o)&&a(l)&&(t(l,o),Object.keys(l).length||delete e[i])}}},{"./is_array":164,"./is_plain_object":165}],181:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("./loggers");function i(t,e){return t<e}function o(t,e){return t<=e}function l(t,e){return t>e}function s(t,e){return t>=e}r.findBin=function(t,e,r){if(n(e.start))return r?Math.ceil((t-e.start)/e.size-1e-9)-1:Math.floor((t-e.start)/e.size+1e-9);var c,u,f=0,d=e.length,p=0,h=d>1?(e[d-1]-e[0])/(d-1):1;for(u=h>=0?r?i:o:r?s:l,t+=1e-9*h*(r?-1:1)*(h>=0?1:-1);f<d&&p++<100;)u(e[c=Math.floor((f+d)/2)],t)?f=c+1:d=c;return p>90&&a.log("Long binary search..."),f-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,a=e[n]-e[0]||1,i=a/(n||1)/1e4,o=[e[0]],l=0;l<n;l++)e[l+1]>e[l]+i&&(a=Math.min(a,e[l+1]-e[l]),o.push(e[l+1]));return{vals:o,minDiff:a}},r.roundUp=function(t,e,r){for(var n,a=0,i=e.length-1,o=0,l=r?0:1,s=r?1:0,c=r?Math.ceil:Math.floor;a<i&&o++<100;)e[n=c((a+i)/2)]<=t?a=n+l:i=n-s;return e[a]}},{"./loggers":168,"fast-isnumeric":13}],182:[function(t,e,r){"use strict";e.exports=function(t,e){(t.attr("class")||"").split(" ").forEach(function(e){0===e.indexOf("cursor-")&&t.classed(e,!1)}),e&&t.classed("cursor-"+e,!0)}},{}],183:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("./is_array").isArrayOrTypedArray;r.aggNums=function(t,e,i,o){var l,s;if((!o||o>i.length)&&(o=i.length),n(e)||(e=!1),a(i[0])){for(s=new Array(o),l=0;l<o;l++)s[l]=r.aggNums(t,e,i[l]);i=s}for(l=0;l<o;l++)n(e)?n(i[l])&&(e=t(+e,+i[l])):e=i[l];return e},r.len=function(t){return r.aggNums(function(t){return t+1},0,t)},r.mean=function(t,e){return e||(e=r.len(t)),r.aggNums(function(t,e){return t+e},0,t)/e},r.midRange=function(t){if(void 0!==t&&0!==t.length)return(r.aggNums(Math.max,null,t)+r.aggNums(Math.min,null,t))/2},r.variance=function(t,e,a){return e||(e=r.len(t)),n(a)||(a=r.mean(t,e)),r.aggNums(function(t,e){return t+Math.pow(e-a,2)},0,t)/e},r.stdev=function(t,e,n){return Math.sqrt(r.variance(t,e,n))},r.interp=function(t,e){if(!n(e))throw"n should be a finite number";if((e=e*t.length-.5)<0)return t[0];if(e>t.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"./is_array":164,"fast-isnumeric":13}],184:[function(t,e,r){"use strict";var n=t("d3"),a=t("../lib"),i=t("../constants/xmlns_namespaces"),o=t("../constants/string_mappings"),l=t("../constants/alignment").LINE_SPACING;function s(t,e){return t.node().getBoundingClientRect()[e]}var c=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;r.convertToTspans=function(t,e,o){var v=t.text(),S=!t.attr("data-notex")&&"undefined"!=typeof MathJax&&v.match(c),O=n.select(t.node().parentNode);if(!O.empty()){var P=t.attr("class")?t.attr("class").split(" ")[0]:"text";return P+="-math",O.selectAll("svg."+P).remove(),O.selectAll("g."+P+"-group").remove(),t.style("display",null).attr({"data-unformatted":v,"data-math":"N"}),S?(e&&e._promises||[]).push(new Promise(function(e){t.style("display","none");var r=parseInt(t.node().style.fontSize,10),i={fontSize:r};!function(t,e,r){var i="math-output-"+a.randstr({},64),o=n.select("body").append("div").attr({id:i}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text((l=t,l.replace(u,"\\lt ").replace(f,"\\gt ")));var l;MathJax.Hub.Queue(["Typeset",MathJax.Hub,o.node()],function(){var e=n.select("body").select("#MathJax_SVG_glyphs");if(o.select(".MathJax_SVG").empty()||!o.select("svg").node())a.log("There was an error in the tex syntax.",t),r();else{var i=o.select("svg").node().getBoundingClientRect();r(o.select(".MathJax_SVG"),e,i)}o.remove()})}(S[2],i,function(n,a,i){O.selectAll("svg."+P).remove(),O.selectAll("g."+P+"-group").remove();var l=n&&n.select("svg");if(!l||!l.node())return D(),void e();var c=O.append("g").classed(P+"-group",!0).attr({"pointer-events":"none","data-unformatted":v,"data-math":"Y"});c.node().appendChild(l.node()),a&&a.node()&&l.node().insertBefore(a.node().cloneNode(!0),l.node().firstChild),l.attr({class:P,height:i.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var u=t.node().style.fill||"black";l.select("g").attr({fill:u,stroke:u});var f=s(l,"width"),d=s(l,"height"),p=+t.attr("x")-f*{start:0,middle:.5,end:1}[t.attr("text-anchor")||"start"],h=-(r||s(t,"height"))/4;"y"===P[0]?(c.attr({transform:"rotate("+[-90,+t.attr("x"),+t.attr("y")]+") translate("+[-f/2,h-d/2]+")"}),l.attr({x:+t.attr("x"),y:+t.attr("y")})):"l"===P[0]?l.attr({x:t.attr("x"),y:h-d/2}):"a"===P[0]?l.attr({x:0,y:h}):l.attr({x:p,y:+t.attr("y")+h-d/2}),o&&o.call(t,c),e(c)})})):D(),t}function D(){O.empty()||(P=t.attr("class")+"-math",O.select("svg."+P).remove()),t.text("").style("white-space","pre"),function(t,e){e=(r=e,function(t,e){if(!t)return"";for(var r=0;r<e.length;r++){var n=e[r];t=t.replace(n.regExp,n.sub)}return t}(r,m)).replace(x," ");var r;var o,s=!1,c=[],u=-1;function f(){u++;var e=document.createElementNS(i.svg,"tspan");n.select(e).attr({class:"line",dy:u*l+"em"}),t.appendChild(e),o=e;var r=c;if(c=[{node:e}],r.length>1)for(var a=1;a<r.length;a++)v(r[a])}function v(t){var e,r=t.type,a={};if("a"===r){e="a";var l=t.target,s=t.href,u=t.popup;s&&(a={"xlink:xlink:show":"_blank"===l||"_"!==l.charAt(0)?"new":"replace",target:l,"xlink:xlink:href":s},u&&(a.onclick='window.open(this.href.baseVal,this.target.baseVal,"'+u+'");return false;'))}else e="tspan";t.style&&(a.style=t.style);var f=document.createElementNS(i.svg,e);if("sup"===r||"sub"===r){S(o,g),o.appendChild(f);var d=document.createElementNS(i.svg,"tspan");S(d,g),n.select(d).attr("dy",h[r]),a.dy=p[r],o.appendChild(f),o.appendChild(d)}else o.appendChild(f);n.select(f).attr(a),o=t.node=f,c.push(t)}function S(t,e){t.appendChild(document.createTextNode(e))}function O(t){if(1!==c.length){var r=c.pop();t!==r.type&&a.log("Start tag <"+r.type+"> doesnt match end tag <"+t+">. Pretending it did match.",e),o=c[c.length-1].node}else a.log("Ignoring unexpected end tag </"+t+">.",e)}w.test(e)?f():(o=t,c=[{node:t}]);for(var P=e.split(b),D=0;D<P.length;D++){var z=P[D],E=z.match(_),I=E&&E[2].toLowerCase(),N=d[I];if("br"===I)f();else if(void 0===N)S(o,z);else if(E[1])O(I);else{var R=E[4],F={type:I},j=L(R,k);if(j?(j=j.replace(C,"$1 fill:"),N&&(j+=";"+N)):N&&(j=N),j&&(F.style=j),"a"===I){s=!0;var B=L(R,M);if(B){var H=document.createElement("a");H.href=B,-1!==y.indexOf(H.protocol)&&(F.href=encodeURI(decodeURI(B)),F.target=L(R,T)||"_blank",F.popup=L(R,A))}}v(F)}}return s}(t.node(),v)&&t.style("pointer-events","all"),r.positionText(t),o&&o.call(t)}};var u=/(<|&lt;|&#60;)/g,f=/(>|&gt;|&#62;)/g;var d={sup:"font-size:70%",sub:"font-size:70%",b:"font-weight:bold",i:"font-style:italic",a:"cursor:pointer",span:"",em:"font-style:italic;font-weight:bold"},p={sub:"0.3em",sup:"-0.6em"},h={sub:"-0.21em",sup:"0.42em"},g="\u200b",y=["http:","https:","mailto:","",void 0,":"],v=new RegExp("</?("+Object.keys(d).join("|")+")( [^>]*)?/?>","g"),m=Object.keys(o.entityToUnicode).map(function(t){return{regExp:new RegExp("&"+t+";","g"),sub:o.entityToUnicode[t]}}),x=/(\r\n?|\n)/g,b=/(<[^<>]*>)/,_=/<(\/?)([^ >]*)(\s+(.*))?>/i,w=/<br(\s+.*)?>/i,k=/(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i,M=/(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i,T=/(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i,A=/(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;function L(t,e){if(!t)return null;var r=t.match(e);return r&&(r[3]||r[4])}var C=/(^|;)\s*color:/;function S(t,e,r){var n,a,i,o=r.horizontalAlign,l=r.verticalAlign||"top",s=t.node().getBoundingClientRect(),c=e.node().getBoundingClientRect();return a="bottom"===l?function(){return s.bottom-n.height}:"middle"===l?function(){return s.top+(s.height-n.height)/2}:function(){return s.top},i="right"===o?function(){return s.right-n.width}:"center"===o?function(){return s.left+(s.width-n.width)/2}:function(){return s.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:a()-c.top+"px",left:i()-c.left+"px","z-index":1e3}),this}}r.plainText=function(t){return(t||"").replace(v," ")},r.lineCount=function(t){return t.selectAll("tspan.line").size()||1},r.positionText=function(t,e,r){return t.each(function(){var t=n.select(this);function a(e,r){return void 0===r?null===(r=t.attr(e))&&(t.attr(e,0),r=0):t.attr(e,r),r}var i=a("x",e),o=a("y",r);"text"===this.nodeName&&t.selectAll("tspan.line").attr({x:i,y:o})})},r.makeEditable=function(t,e){var r=e.gd,a=e.delegate,i=n.dispatch("edit","input","cancel"),o=a||t;if(t.style({"pointer-events":a?"none":"all"}),1!==t.size())throw new Error("boo");function l(){!function(){var a=n.select(r).select(".svg-container"),o=a.append("div"),l=t.node().style,c=parseFloat(l.fontSize||12),u=e.text;void 0===u&&(u=t.attr("data-unformatted"));o.classed("plugin-editable editable",!0).style({position:"absolute","font-family":l.fontFamily||"Arial","font-size":c,color:e.fill||l.fill||"black",opacity:1,"background-color":e.background||"transparent",outline:"#ffffff33 1px solid",margin:[-c/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(u).call(S(t,a,e)).on("blur",function(){r._editing=!1,t.text(this.textContent).style({opacity:1});var e,a=n.select(this).attr("class");(e=a?"."+a.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(e).style({opacity:0});var o=this.textContent;n.select(this).transition().duration(0).remove(),n.select(document).on("mouseup",null),i.edit.call(t,o)}).on("focus",function(){var t=this;r._editing=!0,n.select(document).on("mouseup",function(){if(n.event.target===t)return!1;document.activeElement===o.node()&&o.node().blur()})}).on("keyup",function(){27===n.event.which?(r._editing=!1,t.style({opacity:1}),n.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),i.cancel.call(t,this.textContent)):(i.input.call(t,this.textContent),n.select(this).call(S(t,a,e)))}).on("keydown",function(){13===n.event.which&&this.blur()}).call(s)}(),t.style({opacity:0});var a,l=o.attr("class");(a=l?"."+l.split(" ")[0]+"-math-group":"[class*=-math-group]")&&n.select(t.node().parentNode).select(a).style({opacity:0})}function s(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}return e.immediate?l():o.on("click",l),n.rebind(t,i,"on")}},{"../constants/alignment":143,"../constants/string_mappings":146,"../constants/xmlns_namespaces":147,"../lib":163,d3:10}],185:[function(t,e,r){"use strict";var n={};function a(t){t&&null!==t.timer&&(clearTimeout(t.timer),t.timer=null)}r.throttle=function(t,e,r){var i=n[t],o=Date.now();if(!i){for(var l in n)n[l].ts<o-6e4&&delete n[l];i=n[t]={ts:0,timer:null}}function s(){r(),i.ts=Date.now(),i.onDone&&(i.onDone(),i.onDone=null)}a(i),o>i.ts+e?s():i.timer=setTimeout(function(){s(),i.timer=null},e)},r.done=function(t){var e=n[t];return e&&e.timer?new Promise(function(t){var r=e.onDone;e.onDone=function(){r&&r(),t(),e.onDone=null}}):Promise.resolve()},r.clear=function(t){if(t)a(n[t]),delete n[t];else for(var e in n)r.clear(e)}},{}],186:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t,e){if(t>0)return Math.log(t)/Math.LN10;var r=Math.log(Math.min(e[0],e[1]))/Math.LN10;return n(r)||(r=Math.log(Math.max(e[0],e[1]))/Math.LN10-6),r}},{"fast-isnumeric":13}],187:[function(t,e,r){"use strict";e.exports={moduleType:"locale",name:"en-US",dictionary:{"Click to enter Colorscale title":"Click to enter Colorscale title"},format:{date:"%m/%d/%Y"}}},{}],188:[function(t,e,r){"use strict";e.exports={moduleType:"locale",name:"en",dictionary:{"Click to enter Colorscale title":"Click to enter Colourscale title"},format:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],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"],periods:["AM","PM"],dateTime:"%a %b %e %X %Y",date:"%d/%m/%Y",time:"%H:%M:%S",decimal:".",thousands:",",grouping:[3],currency:["$",""],year:"%Y",month:"%b %Y",dayMonth:"%b %-d",dayMonthYear:"%b %-d, %Y"}}},{}],189:[function(t,e,r){"use strict";var n=t("../registry");e.exports=function(t){for(var e,r,a=n.layoutArrayContainers,i=n.layoutArrayRegexes,o=t.split("[")[0],l=0;l<i.length;l++)if((r=t.match(i[l]))&&0===r.index){e=r[0];break}if(e||(e=a[a.indexOf(o)]),!e)return!1;var s=t.substr(e.length);return s?!!(r=s.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/))&&{array:e,index:Number(r[1]),property:r[3]||""}:{array:e,index:"",property:""}}},{"../registry":247}],190:[function(t,e,r){"use strict";var n=t("../lib"),a=n.extendFlat,i=n.isPlainObject,o={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","clearAxisTypes","plot","style","colorbars"]},l={valType:"flaglist",extras:["none"],flags:["calc","calcIfAutorange","plot","legend","ticks","axrange","layoutstyle","modebar","camera","arraydraw"]},s=o.flags.slice().concat(["clearCalc","fullReplot"]),c=l.flags.slice().concat("layoutReplot");function u(t){for(var e={},r=0;r<t.length;r++)e[t[r]]=!1;return e}function f(t,e,r){var n=a({},t);for(var o in n){var l=n[o];i(l)&&(n[o]=d(l,e,r,o))}return"from-root"===r&&(n.editType=e),n}function d(t,e,r,n){if(t.valType){var i=a({},t);if(i.editType=e,Array.isArray(t.items)){i.items=new Array(t.items.length);for(var o=0;o<t.items.length;o++)i.items[o]=d(t.items[o],e,"from-root")}return i}return f(t,e,"_"===n.charAt(0)?"nested":"from-root")}e.exports={traces:o,layout:l,traceFlags:function(){return u(s)},layoutFlags:function(){return u(c)},update:function(t,e){var r=e.editType;if(r&&"none"!==r)for(var n=r.split("+"),a=0;a<n.length;a++)t[n[a]]=!0},overrideAll:f}},{"../lib":163}],191:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("gl-mat4/fromQuat"),i=t("../registry"),o=t("../lib"),l=t("../plots/plots"),s=t("../plots/cartesian/axis_ids"),c=s.cleanId,u=s.getFromTrace,f=t("../components/color");function d(t,e){var r=t[e],n=e.charAt(0);r&&"paper"!==r&&(t[e]=c(r,n))}function p(t){if(!o.isPlainObject(t))return!1;var e=t.name;return delete t.name,delete t.showlegend,("string"==typeof e||"number"==typeof e)&&String(e)}function h(t,e,r,n){if(r&&!n)return t;if(n&&!r)return e;if(!t.trim())return e;if(!e.trim())return t;var a,i=Math.min(t.length,e.length);for(a=0;a<i&&t.charAt(a)===e.charAt(a);a++);return t.substr(0,a).trim()}function g(t){var e="middle",r="center";return-1!==t.indexOf("top")?e="top":-1!==t.indexOf("bottom")&&(e="bottom"),-1!==t.indexOf("left")?r="left":-1!==t.indexOf("right")&&(r="right"),e+" "+r}function y(t,e){return e in t&&"object"==typeof t[e]&&0===Object.keys(t[e]).length}r.clearPromiseQueue=function(t){Array.isArray(t._promises)&&t._promises.length>0&&o.log("Clearing previous rejected promises from queue."),t._promises=[]},r.cleanLayout=function(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var n=(l.subplotsRegistry.cartesian||{}).attrRegex,i=(l.subplotsRegistry.gl3d||{}).attrRegex,s=Object.keys(t);for(e=0;e<s.length;e++){var u=s[e];if(n&&n.test(u)){var p=t[u];p.anchor&&"free"!==p.anchor&&(p.anchor=c(p.anchor)),p.overlaying&&(p.overlaying=c(p.overlaying)),p.type||(p.isdate?p.type="date":p.islog?p.type="log":!1===p.isdate&&!1===p.islog&&(p.type="linear")),"withzero"!==p.autorange&&"tozero"!==p.autorange||(p.autorange=!0,p.rangemode="tozero"),delete p.islog,delete p.isdate,delete p.categories,y(p,"domain")&&delete p.domain,void 0!==p.autotick&&(void 0===p.tickmode&&(p.tickmode=p.autotick?"auto":"linear"),delete p.autotick)}else if(i&&i.test(u)){var h=t[u],g=h.cameraposition;if(Array.isArray(g)&&4===g[0].length){var v=g[0],m=g[1],x=g[2],b=a([],v),_=[];for(r=0;r<3;++r)_[r]=m[r]+x*b[2+4*r];h.camera={eye:{x:_[0],y:_[1],z:_[2]},center:{x:m[0],y:m[1],z:m[2]},up:{x:b[1],y:b[5],z:b[9]}},delete h.cameraposition}}}var w=Array.isArray(t.annotations)?t.annotations.length:0;for(e=0;e<w;e++){var k=t.annotations[e];o.isPlainObject(k)&&(k.ref&&("paper"===k.ref?(k.xref="paper",k.yref="paper"):"data"===k.ref&&(k.xref="x",k.yref="y"),delete k.ref),d(k,"xref"),d(k,"yref"))}var M=Array.isArray(t.shapes)?t.shapes.length:0;for(e=0;e<M;e++){var T=t.shapes[e];o.isPlainObject(T)&&(d(T,"xref"),d(T,"yref"))}var A=t.legend;return A&&(A.x>3?(A.x=1.02,A.xanchor="left"):A.x<-2&&(A.x=-.02,A.xanchor="right"),A.y>3?(A.y=1.02,A.yanchor="bottom"):A.y<-2&&(A.y=-.02,A.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),f.clean(t),t},r.cleanData=function(t){for(var e=0;e<t.length;e++){var n,a=t[e];if("histogramy"===a.type&&"xbins"in a&&!("ybins"in a)&&(a.ybins=a.xbins,delete a.xbins),a.error_y&&"opacity"in a.error_y){var s=f.defaults,u=a.error_y.color||(i.traceIs(a,"bar")?f.defaultLine:s[e%s.length]);a.error_y.color=f.addOpacity(f.rgb(u),f.opacity(u)*a.error_y.opacity),delete a.error_y.opacity}if("bardir"in a&&("h"!==a.bardir||!i.traceIs(a,"bar")&&"histogram"!==a.type.substr(0,9)||(a.orientation="h",r.swapXYData(a)),delete a.bardir),"histogramy"===a.type&&r.swapXYData(a),"histogramx"!==a.type&&"histogramy"!==a.type||(a.type="histogram"),"scl"in a&&(a.colorscale=a.scl,delete a.scl),"reversescl"in a&&(a.reversescale=a.reversescl,delete a.reversescl),a.xaxis&&(a.xaxis=c(a.xaxis,"x")),a.yaxis&&(a.yaxis=c(a.yaxis,"y")),i.traceIs(a,"gl3d")&&a.scene&&(a.scene=l.subplotsRegistry.gl3d.cleanId(a.scene)),!i.traceIs(a,"pie")&&!i.traceIs(a,"bar"))if(Array.isArray(a.textposition))for(n=0;n<a.textposition.length;n++)a.textposition[n]=g(a.textposition[n]);else a.textposition&&(a.textposition=g(a.textposition));var d=i.getModule(a);if(d&&d.colorbar){var v=d.colorbar.container,m=v?a[v]:a;m&&m.colorscale&&("YIGnBu"===m.colorscale&&(m.colorscale="YlGnBu"),"YIOrRd"===m.colorscale&&(m.colorscale="YlOrRd"))}if("surface"===a.type&&o.isPlainObject(a.contours)){var x=["x","y","z"];for(n=0;n<x.length;n++){var b=a.contours[x[n]];o.isPlainObject(b)&&(b.highlightColor&&(b.highlightcolor=b.highlightColor,delete b.highlightColor),b.highlightWidth&&(b.highlightwidth=b.highlightWidth,delete b.highlightWidth))}}if("candlestick"===a.type||"ohlc"===a.type){var _=!1!==(a.increasing||{}).showlegend,w=!1!==(a.decreasing||{}).showlegend,k=p(a.increasing),M=p(a.decreasing);if(!1!==k&&!1!==M){var T=h(k,M,_,w);T&&(a.name=T)}else!k&&!M||a.name||(a.name=k||M)}if(Array.isArray(a.transforms)){var A=a.transforms;for(n=0;n<A.length;n++){var L=A[n];if(o.isPlainObject(L))switch(L.type){case"filter":L.filtersrc&&(L.target=L.filtersrc,delete L.filtersrc),L.calendar&&(L.valuecalendar||(L.valuecalendar=L.calendar),delete L.calendar);break;case"groupby":if(L.styles=L.styles||L.style,L.styles&&!Array.isArray(L.styles)){var C=L.styles,S=Object.keys(C);L.styles=[];for(var O=0;O<S.length;O++)L.styles.push({target:S[O],value:C[S[O]]})}}}}y(a,"line")&&delete a.line,"marker"in a&&(y(a.marker,"line")&&delete a.marker.line,y(a,"marker")&&delete a.marker),f.clean(a)}},r.swapXYData=function(t){var e;if(o.swapAttrs(t,["?","?0","d?","?bins","nbins?","autobin?","?src","error_?"]),Array.isArray(t.z)&&Array.isArray(t.z[0])&&(t.transpose?delete t.transpose:t.transpose=!0),t.error_x&&t.error_y){var r=t.error_y,n="copy_ystyle"in r?r.copy_ystyle:!(r.color||r.thickness||r.width);o.swapAttrs(t,["error_?.copy_ystyle"]),n&&o.swapAttrs(t,["error_?.color","error_?.thickness","error_?.width"])}if("string"==typeof t.hoverinfo){var a=t.hoverinfo.split("+");for(e=0;e<a.length;e++)"x"===a[e]?a[e]="y":"y"===a[e]&&(a[e]="x");t.hoverinfo=a.join("+")}},r.coerceTraceIndices=function(t,e){return n(e)?[e]:Array.isArray(e)&&e.length?e:t.data.map(function(t,e){return e})},r.manageArrayContainers=function(t,e,r){var a=t.obj,i=t.parts,l=i.length,s=i[l-1],c=n(s);if(c&&null===e){var u=i.slice(0,l-1).join(".");o.nestedProperty(a,u).get().splice(s,1)}else c&&void 0===t.get()?(void 0===t.get()&&(r[t.astr]=null),t.set(e)):t.set(e)};var v=/(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;function m(t){var e=t.search(v);if(e>0)return t.substr(0,e)}r.hasParent=function(t,e){for(var r=m(e);r;){if(r in t)return!0;r=m(r)}return!1};var x=["x","y","z"];r.clearAxisTypes=function(t,e,r){for(var n=0;n<e.length;n++)for(var a=t._fullData[n],i=0;i<3;i++){var l=u(t,a,x[i]);if(l&&"log"!==l.type){var s=l._name,c=l._id.substr(1);if("scene"===c.substr(0,5)){if(void 0!==r[c])continue;s=c+"."+s}var f=s+".type";void 0===r[s]&&void 0===r[f]&&o.nestedProperty(t.layout,f).set(null)}}}},{"../components/color":45,"../lib":163,"../plots/cartesian/axis_ids":210,"../plots/plots":239,"../registry":247,"fast-isnumeric":13,"gl-mat4/fromQuat":14}],192:[function(t,e,r){"use strict";var n=t("./plot_api");r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.relayout=n.relayout,r.redraw=n.redraw,r.update=n.update,r.react=n.react,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.purge=n.purge,r.addFrames=n.addFrames,r.deleteFrames=n.deleteFrames,r.animate=n.animate,r.setPlotConfig=n.setPlotConfig,r.toImage=t("./to_image"),r.validate=t("./validate"),r.downloadImage=t("../snapshot/download");var a=t("./template_api");r.makeTemplate=a.makeTemplate,r.validateTemplate=a.validateTemplate},{"../snapshot/download":249,"./plot_api":194,"./template_api":199,"./to_image":200,"./validate":201}],193:[function(t,e,r){"use strict";var n=t("../lib/nested_property"),a=t("../lib/is_plain_object"),i=t("../lib/noop"),o=t("../lib/loggers"),l=t("../lib/search").sorterAsc,s=t("../registry");r.containerArrayMatch=t("./container_array_match");var c=r.isAddVal=function(t){return"add"===t||a(t)},u=r.isRemoveVal=function(t){return null===t||"remove"===t};r.applyContainerArrayChanges=function(t,e,r,a){var f=e.astr,d=s.getComponentMethod(f,"supplyLayoutDefaults"),p=s.getComponentMethod(f,"draw"),h=s.getComponentMethod(f,"drawOne"),g=a.replot||a.recalc||d===i||p===i,y=t.layout,v=t._fullLayout;if(r[""]){Object.keys(r).length>1&&o.warn("Full array edits are incompatible with other edits",f);var m=r[""][""];if(u(m))e.set(null);else{if(!Array.isArray(m))return o.warn("Unrecognized full array edit value",f,m),!0;e.set(m)}return!g&&(d(y,v),p(t),!0)}var x,b,_,w,k,M,T,A=Object.keys(r).map(Number).sort(l),L=e.get(),C=L||[],S=n(v,f).get(),O=[],P=-1,D=C.length;for(x=0;x<A.length;x++)if(w=r[_=A[x]],k=Object.keys(w),M=w[""],T=c(M),_<0||_>C.length-(T?0:1))o.warn("index out of range",f,_);else if(void 0!==M)k.length>1&&o.warn("Insertion & removal are incompatible with edits to the same index.",f,_),u(M)?O.push(_):T?("add"===M&&(M={}),C.splice(_,0,M),S&&S.splice(_,0,{})):o.warn("Unrecognized full object edit value",f,_,M),-1===P&&(P=_);else for(b=0;b<k.length;b++)n(C[_],k[b]).set(w[k[b]]);for(x=O.length-1;x>=0;x--)C.splice(O[x],1),S&&S.splice(O[x],1);if(C.length?L||e.set(C):e.set(null),g)return!1;if(d(y,v),h!==i){var z;if(-1===P)z=A;else{for(D=Math.max(C.length,D),z=[],x=0;x<A.length&&!((_=A[x])>=P);x++)z.push(_);for(x=P;x<D;x++)z.push(x)}for(x=0;x<z.length;x++)h(t,z[x])}else p(t);return!0}},{"../lib/is_plain_object":165,"../lib/loggers":168,"../lib/nested_property":171,"../lib/noop":172,"../lib/search":181,"../registry":247,"./container_array_match":189}],194:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("has-hover"),o=t("../lib"),l=t("../lib/events"),s=t("../lib/queue"),c=t("../registry"),u=t("./plot_schema"),f=t("../plots/plots"),d=t("../plots/polar/legacy"),p=t("../plots/cartesian/axes"),h=t("../components/drawing"),g=t("../components/color"),y=t("../components/colorbar/connect"),v=t("../plots/cartesian/graph_interact").initInteractions,m=t("../constants/xmlns_namespaces"),x=t("../lib/svg_text_utils"),b=t("./plot_config"),_=t("./manage_arrays"),w=t("./helpers"),k=t("./subroutines"),M=t("./edit_types"),T=t("../plots/cartesian/constants").AX_NAME_PATTERN,A=0;function L(t){var e=t._fullLayout;e._redrawFromAutoMarginCount?e._redrawFromAutoMarginCount--:t.emit("plotly_afterplot")}function C(t,e){try{t._fullLayout._paper.style("background",e)}catch(t){o.error(t)}}function S(t,e){C(t,g.combine(e,"white"))}function O(t,e){t._context||(t._context=o.extendDeep({},b));var r,n,a,l=t._context;if(e){for(n=Object.keys(e),r=0;r<n.length;r++)"editable"!==(a=n[r])&&"edits"!==a&&a in l&&("setBackground"===a&&"opaque"===e[a]?l[a]=S:l[a]=e[a]);e.plot3dPixelRatio&&!l.plotGlPixelRatio&&(l.plotGlPixelRatio=l.plot3dPixelRatio);var s=e.editable;if(void 0!==s)for(l.editable=s,n=Object.keys(l.edits),r=0;r<n.length;r++)l.edits[n[r]]=s;if(e.edits)for(n=Object.keys(e.edits),r=0;r<n.length;r++)(a=n[r])in l.edits&&(l.edits[a]=e.edits[a])}l.staticPlot&&(l.editable=!1,l.edits={},l.autosizable=!1,l.scrollZoom=!1,l.doubleClick=!1,l.showTips=!1,l.showLink=!1,l.displayModeBar=!1),"hover"!==l.displayModeBar||i||(l.displayModeBar=!0),"transparent"!==l.setBackground&&"function"==typeof l.setBackground||(l.setBackground=C)}function P(t,e){var r,n,a=e+1,i=[];for(r=0;r<t.length;r++)(n=t[r])<0?i.push(a+n):i.push(n);return i}function D(t,e,r){var n,a;for(n=0;n<e.length;n++){if((a=e[n])!==parseInt(a,10))throw new Error("all values in "+r+" must be integers");if(a>=t.data.length||a<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(a,n+1)>-1||a>=0&&e.indexOf(-t.data.length+a)>-1||a<0&&e.indexOf(t.data.length+a)>-1)throw new Error("each index in "+r+" must be unique.")}}function z(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),D(t,e,"currentIndices"),"undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&D(t,r,"newIndices"),"undefined"!=typeof r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function E(t,e,r,n,i){!function(t,e,r,n){var a=o.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!o.isPlainObject(e))throw new Error("update must be a key:value object");if("undefined"==typeof r)throw new Error("indices must be an integer or array of integers");for(var i in D(t,r,"indices"),e){if(!Array.isArray(e[i])||e[i].length!==r.length)throw new Error("attribute "+i+" must be an array of length equal to indices array length");if(a&&(!(i in n)||!Array.isArray(n[i])||n[i].length!==e[i].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}(t,e,r,n);for(var l=function(t,e,r,n){var i,l,s,c,u,f=o.isPlainObject(n),d=[];for(var p in Array.isArray(r)||(r=[r]),r=P(r,t.data.length-1),e)for(var h=0;h<r.length;h++){if(i=t.data[r[h]],l=(s=o.nestedProperty(i,p)).get(),c=e[p][h],!o.isArrayOrTypedArray(c))throw new Error("attribute: "+p+" index: "+h+" must be an array");if(!o.isArrayOrTypedArray(l))throw new Error("cannot extend missing or non-array attribute: "+p);if(l.constructor!==c.constructor)throw new Error("cannot extend array with an array of a different type: "+p);u=f?n[p][h]:n,a(u)||(u=-1),d.push({prop:s,target:l,insert:c,maxp:Math.floor(u)})}return d}(t,e,r,n),s={},c={},u=0;u<l.length;u++){var f=l[u].prop,d=l[u].maxp,p=i(l[u].target,l[u].insert,d);f.set(p[0]),Array.isArray(s[f.astr])||(s[f.astr]=[]),s[f.astr].push(p[1]),Array.isArray(c[f.astr])||(c[f.astr]=[]),c[f.astr].push(l[u].target.length)}return{update:s,maxPoints:c}}function I(t,e){var r=new t.constructor(t.length+e.length);return r.set(t),r.set(e,t.length),r}function N(t){return void 0===t?null:t}function R(t,e,r){var n,a,i=t._fullLayout,l=t._fullData,s=t.data,d=M.traceFlags(),h={},g={};function y(){return r.map(function(){})}function v(t){var e=p.id2name(t);-1===a.indexOf(e)&&a.push(e)}function m(t){return"LAYOUT"+t+".autorange"}function x(t){return"LAYOUT"+t+".range"}function b(n,a,i){var l;Array.isArray(n)?n.forEach(function(t){b(t,a,i)}):n in e||w.hasParent(e,n)||(l="LAYOUT"===n.substr(0,6)?o.nestedProperty(t.layout,n.replace("LAYOUT","")):o.nestedProperty(s[r[i]],n),n in g||(g[n]=y()),void 0===g[n][i]&&(g[n][i]=N(l.get())),void 0!==a&&l.set(a))}for(var _ in e){if(w.hasParent(e,_))throw new Error("cannot set "+_+"and a parent attribute simultaneously");var k,T,A,L,C,S,O=e[_];if(h[_]=O,"LAYOUT"!==_.substr(0,6)){for(g[_]=y(),n=0;n<r.length;n++)if(k=s[r[n]],T=l[r[n]],L=(A=o.nestedProperty(k,_)).get(),void 0!==(C=Array.isArray(O)?O[n%O.length]:O)){var P=A.parts[A.parts.length-1],D=_.substr(0,_.length-P.length-1),z=D?D+".":"",E=D?o.nestedProperty(T,D).get():T;if((S=u.getTraceValObject(T,A.parts))&&S.impliedEdits&&null!==C)for(var I in S.impliedEdits)b(o.relativeAttr(_,I),S.impliedEdits[I],n);else if("thicknessmode"!==P&&"lenmode"!==P||L===C||"fraction"!==C&&"pixels"!==C||!E){if("type"===_&&"pie"===C!=("pie"===L)){var R="x",F="y";"bar"!==C&&"bar"!==L||"h"!==k.orientation||(R="y",F="x"),o.swapAttrs(k,["?","?src"],"labels",R),o.swapAttrs(k,["d?","?0"],"label",R),o.swapAttrs(k,["?","?src"],"values",F),"pie"===L?(o.nestedProperty(k,"marker.color").set(o.nestedProperty(k,"marker.colors").get()),i._pielayer.selectAll("g.trace").remove()):c.traceIs(k,"cartesian")&&o.nestedProperty(k,"marker.colors").set(o.nestedProperty(k,"marker.color").get())}}else{var j=i._size,B=E.orient,H="top"===B||"bottom"===B;if("thicknessmode"===P){var q=H?j.h:j.w;b(z+"thickness",E.thickness*("fraction"===C?1/q:q),n)}else{var V=H?j.w:j.h;b(z+"len",E.len*("fraction"===C?1/V:V),n)}}g[_][n]=N(L);if(-1!==["swapxy","swapxyaxes","orientation","orientationaxes"].indexOf(_)){if("orientation"===_){A.set(C);var U=k.x&&!k.y?"h":"v";if((A.get()||U)===T.orientation)continue}else"orientationaxes"===_&&(k.orientation={v:"h",h:"v"}[T.orientation]);w.swapXYData(k),d.calc=d.clearAxisTypes=!0}else-1!==f.dataArrayContainers.indexOf(A.parts[0])?(w.manageArrayContainers(A,C,g),d.calc=!0):(S?S.arrayOk&&(o.isArrayOrTypedArray(C)||o.isArrayOrTypedArray(L))?d.calc=!0:M.update(d,S):d.calc=!0,A.set(C))}if(-1!==["swapxyaxes","orientationaxes"].indexOf(_)&&p.swap(t,r),"orientationaxes"===_){var G=o.nestedProperty(t.layout,"hovermode");"x"===G.get()?G.set("y"):"y"===G.get()&&G.set("x")}if(-1!==["orientation","type"].indexOf(_)){for(a=[],n=0;n<r.length;n++){var Y=s[r[n]];c.traceIs(Y,"cartesian")&&(v(Y.xaxis||"x"),v(Y.yaxis||"y"),"type"===_&&b(["autobinx","autobiny"],!0,n))}b(a.map(m),!0,0),b(a.map(x),[0,1],0)}}else A=o.nestedProperty(t.layout,_.replace("LAYOUT","")),g[_]=[N(A.get())],A.set(Array.isArray(O)?O[0]:O),d.calc=!0}var X=!1,Z=p.list(t);for(n=0;n<Z.length;n++)if(Z[n].autorange){X=!0;break}return(d.calc||d.calcIfAutorange&&X)&&(d.clearCalc=!0),(d.calc||d.plot||d.calcIfAutorange)&&(d.fullReplot=!0),{flags:d,undoit:g,redoit:h,traces:r,eventData:o.extendDeepNoArrays([],[h,r])}}function F(t,e){var r=e?function(t){return k.doTicksRelayout(t,e)}:k.doTicksRelayout;t.push(r,k.drawData,k.finalDraw)}r.plot=function(t,e,a,i){var s;if(t=o.getGraphDiv(t),l.init(t),o.isPlainObject(e)){var u=e;e=u.data,a=u.layout,i=u.config,s=u.frames}if(!1===l.triggerHandler(t,"plotly_beforeplot",[e,a,i]))return Promise.reject();e||a||o.isPlotDiv(t)||o.warn("Calling Plotly.plot as if redrawing but this container doesn't yet have a plot.",t),O(t,i),a||(a={}),n.select(t).classed("js-plotly-plot",!0),h.makeTester(),delete h.baseUrl,Array.isArray(t._promises)||(t._promises=[]);var g=0===(t.data||[]).length&&Array.isArray(e);if(Array.isArray(e)&&(w.cleanData(e),g?t.data=e:t.data.push.apply(t.data,e),t.empty=!1),t.layout&&!g||(t.layout=w.cleanLayout(a)),t._dragging&&!t._transitioning)return t._replotPending=!0,Promise.reject();t._replotPending=!1,f.supplyDefaults(t);var m=t._fullLayout,b=m._has("cartesian");if(!m._has("polar")&&e&&e[0]&&e[0].r)return o.log("Legacy polar charts are deprecated!"),function(t,e,r){var a=n.select(t).selectAll(".plot-container").data([0]);a.enter().insert("div",":first-child").classed("plot-container plotly",!0);var i=a.selectAll(".svg-container").data([0]);i.enter().append("div").classed("svg-container",!0).style("position","relative"),i.html(""),e&&(t.data=e);r&&(t.layout=r);d.manager.fillLayout(t),i.style({width:t._fullLayout.width+"px",height:t._fullLayout.height+"px"}),t.framework=d.manager.framework(t),t.framework({data:t.data,layout:t.layout},i.node()),t.framework.setUndoPoint();var l=t.framework.svg(),s=1,c=t._fullLayout.title;""!==c&&c||(s=0);var u=function(){this.call(x.convertToTspans,t)},p=l.select(".title-group text").call(u);if(t._context.edits.titleText){var h=o._(t,"Click to enter Plot title");c&&c!==h||(s=.2,p.attr({"data-unformatted":h}).text(h).style({opacity:s}).on("mouseover.opacity",function(){n.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(1e3).style("opacity",0)}));var g=function(){this.call(x.makeEditable,{gd:t}).on("edit",function(e){t.framework({layout:{title:e}}),this.text(e).call(u),this.call(g)}).on("cancel",function(){var t=this.attr("data-unformatted");this.text(t).call(u)})};p.call(g)}return t._context.setBackground(t,t._fullLayout.paper_bgcolor),f.addLinks(t),Promise.resolve()}(t,e,a);m._replotting=!0,g&&Y(t),t.framework!==Y&&(t.framework=Y,Y(t)),h.initGradients(t),g&&p.saveShowSpikeInitial(t);var _=!t.calcdata||t.calcdata.length!==(t._fullData||[]).length;_&&f.doCalcdata(t);for(var M=0;M<t.calcdata.length;M++)t.calcdata[M][0].trace=t._fullData[M];var T=JSON.stringify(m._size);function A(){var e,r,n,a=t.calcdata;for(f.clearAutoMarginIds(t),k.drawMarginPushers(t),p.allowAutoMargin(t),e=0;e<a.length;e++){var i=(n=(r=a[e])[0].trace)._module.colorbar;!0===n.visible&&i?y(t,r,i):f.autoMargin(t,"cb"+n.uid)}return f.doAutoMargin(t),f.previousPromises(t)}function C(){t._transitioning||(k.doAutoRangeAndConstraints(t),g&&p.saveRangeInitial(t))}var S=[f.previousPromises,function(){if(s)return r.addFrames(t,s)},function(){for(var e=m._basePlotModules,r=0;r<e.length;r++)e[r].drawFramework&&e[r].drawFramework(t);return!m._glcanvas&&m._has("gl")&&(m._glcanvas=m._glcontainer.selectAll(".gl-canvas").data([{key:"contextLayer",context:!0,pick:!1},{key:"focusLayer",context:!1,pick:!1},{key:"pickLayer",context:!1,pick:!0}],function(t){return t.key}),m._glcanvas.enter().append("canvas").attr("class",function(t){return"gl-canvas gl-canvas-"+t.key.replace("Layer","")}).style({position:"absolute",top:0,left:0,width:"100%",height:"100%",overflow:"visible","pointer-events":"none"})),m._glcanvas&&m._glcanvas.attr("width",m.width).attr("height",m.height),f.previousPromises(t)},A,function(){if(JSON.stringify(m._size)!==T)return o.syncOrAsync([A,k.layoutStyles],t)}];b&&S.push(function(){if(_)return f.doSetPositions(t),c.getComponentMethod("errorbars","calc")(t),o.syncOrAsync([c.getComponentMethod("shapes","calcAutorange"),c.getComponentMethod("annotations","calcAutorange"),C,c.getComponentMethod("rangeslider","calcAutorange")],t);C()}),S.push(k.layoutStyles),b&&S.push(function(){return p.doTicks(t,g?"":"redraw")}),S.push(k.drawData,k.finalDraw,v,f.addLinks,f.rehover,f.doAutoMargin,f.previousPromises);var P=o.syncOrAsync(S,t);return P&&P.then||(P=Promise.resolve()),P.then(function(){return L(t),t})},r.setPlotConfig=function(t){return o.extendFlat(b,t)},r.redraw=function(t){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t);return w.cleanData(t.data),w.cleanLayout(t.layout),t.calcdata=void 0,r.plot(t).then(function(){return t.emit("plotly_redraw"),t})},r.newPlot=function(t,e,n,a){return t=o.getGraphDiv(t),f.cleanPlot([],{},t._fullData||[],t._fullLayout||{},t.calcdata||[]),f.purge(t),r.plot(t,e,n,a)},r.extendTraces=function t(e,n,a,i){var l=E(e=o.getGraphDiv(e),n,a,i,function(t,e,r){var n,a;if(o.isTypedArray(t))if(r<0){var i=new t.constructor(0),l=I(t,e);r<0?(n=l,a=i):(n=i,a=l)}else if(n=new t.constructor(r),a=new t.constructor(t.length+e.length-r),r===e.length)n.set(e),a.set(t);else if(r<e.length){var s=e.length-r;n.set(e.subarray(s)),a.set(t),a.set(e.subarray(0,s),t.length)}else{var c=r-e.length,u=t.length-c;n.set(t.subarray(u)),n.set(e,c),a.set(t.subarray(0,u))}else n=t.concat(e),a=r>=0&&r<n.length?n.splice(0,n.length-r):[];return[n,a]}),c=r.redraw(e),u=[e,l.update,a,l.maxPoints];return s.add(e,r.prependTraces,u,t,arguments),c},r.prependTraces=function t(e,n,a,i){var l=E(e=o.getGraphDiv(e),n,a,i,function(t,e,r){var n,a;if(o.isTypedArray(t))if(r<=0){var i=new t.constructor(0),l=I(e,t);r<0?(n=l,a=i):(n=i,a=l)}else if(n=new t.constructor(r),a=new t.constructor(t.length+e.length-r),r===e.length)n.set(e),a.set(t);else if(r<e.length){var s=e.length-r;n.set(e.subarray(0,s)),a.set(e.subarray(s)),a.set(t,s)}else{var c=r-e.length;n.set(e),n.set(t.subarray(0,c),e.length),a.set(t.subarray(c))}else n=e.concat(t),a=r>=0&&r<n.length?n.splice(r,n.length):[];return[n,a]}),c=r.redraw(e),u=[e,l.update,a,l.maxPoints];return s.add(e,r.extendTraces,u,t,arguments),c},r.addTraces=function t(e,n,a){e=o.getGraphDiv(e);var i,l,c=[],u=r.deleteTraces,f=t,d=[e,c],p=[e,n];for(function(t,e,r){var n,a;if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("traces must be defined.");for(Array.isArray(e)||(e=[e]),n=0;n<e.length;n++)if("object"!=typeof(a=e[n])||Array.isArray(a)||null===a)throw new Error("all values in traces array must be non-array objects");if("undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&r.length!==e.length)throw new Error("if indices is specified, traces.length must equal indices.length")}(e,n,a),Array.isArray(n)||(n=[n]),n=n.map(function(t){return o.extendFlat({},t)}),w.cleanData(n),i=0;i<n.length;i++)e.data.push(n[i]);for(i=0;i<n.length;i++)c.push(-n.length+i);if("undefined"==typeof a)return l=r.redraw(e),s.add(e,u,d,f,p),l;Array.isArray(a)||(a=[a]);try{z(e,c,a)}catch(t){throw e.data.splice(e.data.length-n.length,n.length),t}return s.startSequence(e),s.add(e,u,d,f,p),l=r.moveTraces(e,c,a),s.stopSequence(e),l},r.deleteTraces=function t(e,n){e=o.getGraphDiv(e);var a,i,l=[],c=r.addTraces,u=t,f=[e,l,n],d=[e,n];if("undefined"==typeof n)throw new Error("indices must be an integer or array of integers.");for(Array.isArray(n)||(n=[n]),D(e,n,"indices"),(n=P(n,e.data.length-1)).sort(o.sorterDes),a=0;a<n.length;a+=1)i=e.data.splice(n[a],1)[0],l.push(i);var p=r.redraw(e);return s.add(e,c,f,u,d),p},r.moveTraces=function t(e,n,a){var i,l=[],c=[],u=t,f=t,d=[e=o.getGraphDiv(e),a,n],p=[e,n,a];if(z(e,n,a),n=Array.isArray(n)?n:[n],"undefined"==typeof a)for(a=[],i=0;i<n.length;i++)a.push(-n.length+i);for(a=Array.isArray(a)?a:[a],n=P(n,e.data.length-1),a=P(a,e.data.length-1),i=0;i<e.data.length;i++)-1===n.indexOf(i)&&l.push(e.data[i]);for(i=0;i<n.length;i++)c.push({newIndex:a[i],trace:e.data[n[i]]});for(c.sort(function(t,e){return t.newIndex-e.newIndex}),i=0;i<c.length;i+=1)l.splice(c[i].newIndex,0,c[i].trace);e.data=l;var h=r.redraw(e);return s.add(e,u,d,f,p),h},r.restyle=function t(e,n,a,i){e=o.getGraphDiv(e),w.clearPromiseQueue(e);var l={};if("string"==typeof n)l[n]=a;else{if(!o.isPlainObject(n))return o.warn("Restyle fail.",n,a,i),Promise.reject();l=o.extendFlat({},n),void 0===i&&(i=a)}Object.keys(l).length&&(e.changed=!0);var c=w.coerceTraceIndices(e,i),u=R(e,l,c),d=u.flags;d.clearCalc&&(e.calcdata=void 0),d.clearAxisTypes&&w.clearAxisTypes(e,c,{});var p=[];d.fullReplot?p.push(r.plot):(p.push(f.previousPromises),f.supplyDefaults(e),d.style&&p.push(k.doTraceStyle),d.colorbars&&p.push(k.doColorBars),p.push(L)),p.push(f.rehover),s.add(e,t,[e,u.undoit,u.traces],t,[e,u.redoit,u.traces]);var h=o.syncOrAsync(p,e);return h&&h.then||(h=Promise.resolve()),h.then(function(){return e.emit("plotly_restyle",u.eventData),e})},r.relayout=function t(e,r,n){if(e=o.getGraphDiv(e),w.clearPromiseQueue(e),e.framework&&e.framework.isPolar)return Promise.resolve(e);var a={};if("string"==typeof r)a[r]=n;else{if(!o.isPlainObject(r))return o.warn("Relayout fail.",r,n),Promise.reject();a=o.extendFlat({},r)}Object.keys(a).length&&(e.changed=!0);var i=q(e,a),l=i.flags;l.calc&&(e.calcdata=void 0);var c=[f.previousPromises];l.layoutReplot?c.push(k.layoutReplot):Object.keys(a).length&&(f.supplyDefaults(e),l.legend&&c.push(k.doLegend),l.layoutstyle&&c.push(k.layoutStyles),l.axrange&&F(c,i.rangesAltered),l.ticks&&c.push(k.doTicksRelayout),l.modebar&&c.push(k.doModeBar),l.camera&&c.push(k.doCamera),c.push(L)),c.push(f.rehover),s.add(e,t,[e,i.undoit],t,[e,i.redoit]);var u=o.syncOrAsync(c,e);return u&&u.then||(u=Promise.resolve(e)),u.then(function(){return e.emit("plotly_relayout",i.eventData),e})};var j=/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/,B=/^[xyz]axis[0-9]*\.autorange$/,H=/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/;function q(t,e){var r,n,a,i=t.layout,l=t._fullLayout,s=Object.keys(e),f=p.list(t),d={};for(n=0;n<s.length;n++)if(0===s[n].indexOf("allaxes")){for(a=0;a<f.length;a++){var h=f[a]._id.substr(1),g=-1!==h.indexOf("scene")?h+".":"",y=s[n].replace("allaxes",g+f[a]._name);e[y]||(e[y]=e[s[n]])}delete e[s[n]]}var v=M.layoutFlags(),m={},x={};function b(t,r){if(Array.isArray(t))t.forEach(function(t){b(t,r)});else if(!(t in e||w.hasParent(e,t))){var n=o.nestedProperty(i,t);t in x||(x[t]=N(n.get())),void 0!==r&&n.set(r)}}var k,A={};function L(t){var e=p.name2id(t.split(".")[0]);return A[e]=1,e}for(var C in e){if(w.hasParent(e,C))throw new Error("cannot set "+C+"and a parent attribute simultaneously");for(var S=o.nestedProperty(i,C),O=e[C],P=S.parts.length-1;P>0&&"string"!=typeof S.parts[P];)P--;var D=S.parts[P],z=S.parts[P-1]+"."+D,E=S.parts.slice(0,P).join("."),I=o.nestedProperty(t.layout,E).get(),R=o.nestedProperty(l,E).get(),F=S.get();if(void 0!==O){m[C]=O,x[C]="reverse"===D?O:N(F);var q=u.getLayoutValObject(l,S.parts);if(q&&q.impliedEdits&&null!==O)for(var G in q.impliedEdits)b(o.relativeAttr(C,G),q.impliedEdits[G]);if(-1!==["width","height"].indexOf(C)&&null===O)l[C]=t._initialAutoSize[C];else if(z.match(j))L(z),o.nestedProperty(l,E+"._inputRange").set(null);else if(z.match(B)){L(z),o.nestedProperty(l,E+"._inputRange").set(null);var Y=o.nestedProperty(l,E).get();Y._inputDomain&&(Y._input.domain=Y._inputDomain.slice())}else z.match(H)&&o.nestedProperty(l,E+"._inputDomain").set(null);if("type"===D){var X=I,Z="linear"===R.type&&"log"===O,W="log"===R.type&&"linear"===O;if(Z||W){if(X&&X.range)if(R.autorange)Z&&(X.range=X.range[1]>X.range[0]?[1,2]:[2,1]);else{var Q=X.range[0],J=X.range[1];Z?(Q<=0&&J<=0&&b(E+".autorange",!0),Q<=0?Q=J/1e6:J<=0&&(J=Q/1e6),b(E+".range[0]",Math.log(Q)/Math.LN10),b(E+".range[1]",Math.log(J)/Math.LN10)):(b(E+".range[0]",Math.pow(10,Q)),b(E+".range[1]",Math.pow(10,J)))}else b(E+".autorange",!0);Array.isArray(l._subplots.polar)&&l._subplots.polar.length&&l[S.parts[0]]&&"radialaxis"===S.parts[1]&&delete l[S.parts[0]]._subplot.viewInitial["radialaxis.range"],c.getComponentMethod("annotations","convertCoords")(t,R,O,b),c.getComponentMethod("images","convertCoords")(t,R,O,b)}else b(E+".autorange",!0),b(E+".range",null);o.nestedProperty(l,E+"._inputRange").set(null)}else if(D.match(T)){var $=o.nestedProperty(l,C).get(),K=(O||{}).type;K&&"-"!==K||(K="linear"),c.getComponentMethod("annotations","convertCoords")(t,$,K,b),c.getComponentMethod("images","convertCoords")(t,$,K,b)}var tt=_.containerArrayMatch(C);if(tt){r=tt.array,n=tt.index;var et=tt.property,rt=(o.nestedProperty(i,r)||[])[n]||{},nt=rt,at=q||{editType:"calc"},it=-1!==at.editType.indexOf("calcIfAutorange");""===n?(it?v.calc=!0:M.update(v,at),it=!1):""===et&&(nt=O,_.isAddVal(O)?x[C]=null:_.isRemoveVal(O)?(x[C]=rt,nt=rt):o.warn("unrecognized full object value",e)),it&&(U(t,nt,"x")||U(t,nt,"y"))?v.calc=!0:M.update(v,at),d[r]||(d[r]={});var ot=d[r][n];ot||(ot=d[r][n]={}),ot[et]=O,delete e[C]}else"reverse"===D?(I.range?I.range.reverse():(b(E+".autorange",!0),I.range=[1,0]),R.autorange?v.calc=!0:v.plot=!0):(l._has("scatter-like")&&l._has("regl")&&"dragmode"===C&&("lasso"===O||"select"===O)&&"lasso"!==F&&"select"!==F?v.plot=!0:q?M.update(v,q):v.calc=!0,S.set(O))}}for(r in d){_.applyContainerArrayChanges(t,o.nestedProperty(i,r),d[r],v)||(v.plot=!0)}var lt=l._axisConstraintGroups||[];for(k in A)for(n=0;n<lt.length;n++){var st=lt[n];if(st[k])for(var ct in v.calc=!0,st)A[ct]||(p.getFromId(t,ct)._constraintShrinkable=!0)}return(V(t)||e.height||e.width)&&(v.plot=!0),(v.plot||v.calc)&&(v.layoutReplot=!0),{flags:v,rangesAltered:A,undoit:x,redoit:m,eventData:o.extendDeep({},m)}}function V(t){var e=t._fullLayout,r=e.width,n=e.height;return t.layout.autosize&&f.plotAutoSize(t,t.layout,e),e.width!==r||e.height!==n}function U(t,e,r){if(!o.isPlainObject(e))return!1;var n=e[r+"ref"]||r,a=p.getFromId(t,n);return a||n.charAt(0)!==r||(a=p.getFromId(t,r)),(a||{}).autorange}function G(t,e,r,n){var a,i,l=n.getValObject,s=n.flags,c=n.immutable,u=n.inArray,f=n.arrayIndex,d=n.gd,p=n.autoranged;function h(){var t=a.editType;-1!==t.indexOf("calcIfAutorange")&&(p||void 0===p&&(U(d,e,"x")||U(d,e,"y")))?s.calc=!0:u&&-1!==t.indexOf("arraydraw")?o.pushUnique(s.arrays[u],f):M.update(s,a)}function g(t){return"data_array"===t.valType||t.arrayOk}for(i in t){if(s.calc)return;var y=t[i],v=e[i];if("_"!==i.charAt(0)&&"function"!=typeof y&&y!==v){if("tick0"===i||"dtick"===i){var m=e.tickmode;if("auto"===m||"array"===m||!m)continue}if(("range"!==i||!e.autorange)&&("zmin"!==i&&"zmax"!==i||"contourcarpet"!==e.type)){var x=r.concat(i);if((a=l(x))&&(!a._compareAsJSON||JSON.stringify(y)!==JSON.stringify(v))){var b,_=a.valType,w=g(a),k=Array.isArray(y),T=Array.isArray(v);if(k&&T){var A="_input_"+i,L=t[A],C=e[A];if(Array.isArray(L)&&L===C)continue}if(void 0===v)w&&k?s.calc=!0:h();else if(a._isLinkedToArray){var S=[],O=!1;u||(s.arrays[i]=S);var P=Math.min(y.length,v.length),D=Math.max(y.length,v.length);if(P!==D){if("arraydraw"!==a.editType){h();continue}O=!0}for(b=0;b<P;b++)G(y[b],v[b],x.concat(b),o.extendFlat({inArray:i,arrayIndex:b},n));if(O)for(b=P;b<D;b++)S.push(b)}else!_&&o.isPlainObject(y)?G(y,v,x,n):w?k&&T?c&&(s.calc=!0):k!==T?s.calc=!0:h():k&&T&&y.length===v.length&&String(y)===String(v)||h()}}}}for(i in e)if(!(i in t||"_"===i.charAt(0)||"function"==typeof e[i])){if(g(a=l(r.concat(i)))&&Array.isArray(e[i]))return void(s.calc=!0);h()}}function Y(t){var e=n.select(t),r=t._fullLayout;if(r._container=e.selectAll(".plot-container").data([0]),r._container.enter().insert("div",":first-child").classed("plot-container",!0).classed("plotly",!0),r._paperdiv=r._container.selectAll(".svg-container").data([0]),r._paperdiv.enter().append("div").classed("svg-container",!0).style("position","relative"),r._glcontainer=r._paperdiv.selectAll(".gl-container").data([{}]),r._glcontainer.enter().append("div").classed("gl-container",!0),r._paperdiv.selectAll(".main-svg").remove(),r._paper=r._paperdiv.insert("svg",":first-child").classed("main-svg",!0),r._toppaper=r._paperdiv.append("svg").classed("main-svg",!0),!r._uid){var a={};n.selectAll("defs").each(function(){this.id&&(a[this.id.split("-")[1]]=1)}),r._uid=o.randstr(a)}r._paperdiv.selectAll(".main-svg").attr(m.svgAttrs),r._defs=r._paper.append("defs").attr("id","defs-"+r._uid),r._clips=r._defs.append("g").classed("clips",!0),r._topdefs=r._toppaper.append("defs").attr("id","topdefs-"+r._uid),r._topclips=r._topdefs.append("g").classed("clips",!0),r._bgLayer=r._paper.append("g").classed("bglayer",!0),r._draggers=r._paper.append("g").classed("draglayer",!0);var i=r._paper.append("g").classed("layer-below",!0);r._imageLowerLayer=i.append("g").classed("imagelayer",!0),r._shapeLowerLayer=i.append("g").classed("shapelayer",!0),r._cartesianlayer=r._paper.append("g").classed("cartesianlayer",!0),r._polarlayer=r._paper.append("g").classed("polarlayer",!0),r._ternarylayer=r._paper.append("g").classed("ternarylayer",!0),r._geolayer=r._paper.append("g").classed("geolayer",!0),r._pielayer=r._paper.append("g").classed("pielayer",!0),r._glimages=r._paper.append("g").classed("glimages",!0);var l=r._toppaper.append("g").classed("layer-above",!0);r._imageUpperLayer=l.append("g").classed("imagelayer",!0),r._shapeUpperLayer=l.append("g").classed("shapelayer",!0),r._infolayer=r._toppaper.append("g").classed("infolayer",!0),r._menulayer=r._toppaper.append("g").classed("menulayer",!0),r._zoomlayer=r._toppaper.append("g").classed("zoomlayer",!0),r._hoverlayer=r._toppaper.append("g").classed("hoverlayer",!0),t.emit("plotly_framework")}r.update=function t(e,n,a,i){if(e=o.getGraphDiv(e),w.clearPromiseQueue(e),e.framework&&e.framework.isPolar)return Promise.resolve(e);o.isPlainObject(n)||(n={}),o.isPlainObject(a)||(a={}),Object.keys(n).length&&(e.changed=!0),Object.keys(a).length&&(e.changed=!0);var l=w.coerceTraceIndices(e,i),c=R(e,o.extendFlat({},n),l),u=c.flags,d=q(e,o.extendFlat({},a)),p=d.flags;(u.clearCalc||p.calc)&&(e.calcdata=void 0),u.clearAxisTypes&&w.clearAxisTypes(e,l,a);var h=[];if(u.fullReplot&&p.layoutReplot){var g=e.data,y=e.layout;e.data=void 0,e.layout=void 0,h.push(function(){return r.plot(e,g,y)})}else u.fullReplot?h.push(r.plot):p.layoutReplot?h.push(k.layoutReplot):(h.push(f.previousPromises),f.supplyDefaults(e),u.style&&h.push(k.doTraceStyle),u.colorbars&&h.push(k.doColorBars),p.legend&&h.push(k.doLegend),p.layoutstyle&&h.push(k.layoutStyles),p.axrange&&F(h,d.rangesAltered),p.ticks&&h.push(k.doTicksRelayout),p.modebar&&h.push(k.doModeBar),p.camera&&h.push(k.doCamera),h.push(L));h.push(f.rehover),s.add(e,t,[e,c.undoit,d.undoit,c.traces],t,[e,c.redoit,d.redoit,c.traces]);var v=o.syncOrAsync(h,e);return v&&v.then||(v=Promise.resolve(e)),v.then(function(){return e.emit("plotly_update",{data:c.eventData,layout:d.eventData}),e})},r.react=function(t,e,n,a){var i,l;var s=(t=o.getGraphDiv(t))._fullData,d=t._fullLayout;if(o.isPlotDiv(t)&&s&&d){if(o.isPlainObject(e)){var h=e;e=h.data,n=h.layout,a=h.config,i=h.frames}var g=!1;if(a){var y=o.extendDeep({},t._context);t._context=void 0,O(t,a),g=function t(e,r){var n;for(n in e){var a=e[n],i=r[n];if(a!==i)if(o.isPlainObject(a)&&o.isPlainObject(i)){if(t(a,i))return!0}else{if(!Array.isArray(a)||!Array.isArray(i))return!0;if(a.length!==i.length)return!0;for(var l=0;l<a.length;l++)if(a[l]!==i[l]){if(!o.isPlainObject(a[l])||!o.isPlainObject(i[l]))return!0;if(t(a[l],i[l]))return!0}}}}(y,t._context)}t.data=e||[],w.cleanData(t.data),t.layout=n||{},w.cleanLayout(t.layout),f.supplyDefaults(t,{skipUpdateCalc:!0});var v=t._fullData,m=t._fullLayout,x=void 0===m.datarevision,b=function(t,e,r,n){if(e.length!==r.length)return{fullReplot:!0,calc:!0};var a,i,o=M.traceFlags();o.arrays={};var l={getValObject:function(t){return u.getTraceValObject(i,t)},flags:o,immutable:n,gd:t},s={};for(a=0;a<e.length;a++)i=r[a]._fullInput,s[i.uid]||(s[i.uid]=1,l.autoranged=!!i.xaxis&&(p.getFromId(t,i.xaxis).autorange||p.getFromId(t,i.yaxis).autorange),G(e[a]._fullInput,i,[],l));(o.calc||o.plot||o.calcIfAutorange)&&(o.fullReplot=!0);return o}(t,s,v,x),_=function(t,e,r,n){var a=M.layoutFlags();a.arrays={},G(e,r,[],{getValObject:function(t){return u.getLayoutValObject(r,t)},flags:a,immutable:n,gd:t}),(a.plot||a.calc)&&(a.layoutReplot=!0);return a}(t,d,m,x);V(t)&&(_.layoutReplot=!0),b.calc||_.calc?t.calcdata=void 0:f.supplyDefaultsUpdateCalc(t.calcdata,v);var T=[];if(i&&(t._transitionData={},f.createTransitionData(t),T.push(function(){return r.addFrames(t,i)})),b.fullReplot||_.layoutReplot||g)t._fullLayout._skipDefaults=!0,T.push(r.plot);else{for(var A in _.arrays){var C=_.arrays[A];if(C.length){var S=c.getComponentMethod(A,"drawOne");if(S!==o.noop)for(var P=0;P<C.length;P++)S(t,C[P]);else{var D=c.getComponentMethod(A,"draw");if(D===o.noop)throw new Error("cannot draw components: "+A);D(t)}}}T.push(f.previousPromises),b.style&&T.push(k.doTraceStyle),b.colorbars&&T.push(k.doColorBars),_.legend&&T.push(k.doLegend),_.layoutstyle&&T.push(k.layoutStyles),_.axrange&&F(T),_.ticks&&T.push(k.doTicksRelayout),_.modebar&&T.push(k.doModeBar),_.camera&&T.push(k.doCamera),T.push(L)}T.push(f.rehover),(l=o.syncOrAsync(T,t))&&l.then||(l=Promise.resolve(t))}else l=r.newPlot(t,e,n,a);return l.then(function(){return t.emit("plotly_react",{data:e,layout:n}),t})},r.animate=function(t,e,r){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t+". It's likely that you've failed to create a plot before animating it. For more details, see https://plot.ly/javascript/animations/");var n=t._transitionData;n._frameQueue||(n._frameQueue=[]);var a=(r=f.supplyAnimationDefaults(r)).transition,i=r.frame;function l(t){return Array.isArray(a)?t>=a.length?a[0]:a[t]:a}function s(t){return Array.isArray(i)?t>=i.length?i[0]:i[t]:i}function c(t,e){var r=0;return function(){if(t&&++r===e)return t()}}return void 0===n._frameWaitingCnt&&(n._frameWaitingCnt=0),new Promise(function(i,u){function d(){n._currentFrame&&n._currentFrame.onComplete&&n._currentFrame.onComplete();var e=n._currentFrame=n._frameQueue.shift();if(e){var r=e.name?e.name.toString():null;t._fullLayout._currentFrame=r,n._lastFrameAt=Date.now(),n._timeToNext=e.frameOpts.duration,f.transition(t,e.frame.data,e.frame.layout,w.coerceTraceIndices(t,e.frame.traces),e.frameOpts,e.transitionOpts).then(function(){e.onComplete&&e.onComplete()}),t.emit("plotly_animatingframe",{name:r,frame:e.frame,animation:{frame:e.frameOpts,transition:e.transitionOpts}})}else t.emit("plotly_animated"),window.cancelAnimationFrame(n._animationRaf),n._animationRaf=null}function p(){t.emit("plotly_animating"),n._lastFrameAt=-1/0,n._timeToNext=0,n._runningTransitions=0,n._currentFrame=null;var e=function(){n._animationRaf=window.requestAnimationFrame(e),Date.now()-n._lastFrameAt>n._timeToNext&&d()};e()}var h,g,y=0;function v(t){return Array.isArray(a)?y>=a.length?t.transitionOpts=a[y]:t.transitionOpts=a[0]:t.transitionOpts=a,y++,t}var m=[],x=null==e,b=Array.isArray(e);if(!x&&!b&&o.isPlainObject(e))m.push({type:"object",data:v(o.extendFlat({},e))});else if(x||-1!==["string","number"].indexOf(typeof e))for(h=0;h<n._frames.length;h++)(g=n._frames[h])&&(x||String(g.group)===String(e))&&m.push({type:"byname",name:String(g.name),data:v({name:g.name})});else if(b)for(h=0;h<e.length;h++){var _=e[h];-1!==["number","string"].indexOf(typeof _)?(_=String(_),m.push({type:"byname",name:_,data:v({name:_})})):o.isPlainObject(_)&&m.push({type:"object",data:v(o.extendFlat({},_))})}for(h=0;h<m.length;h++)if("byname"===(g=m[h]).type&&!n._frameHash[g.data.name])return o.warn('animate failure: frame not found: "'+g.data.name+'"'),void u();-1!==["next","immediate"].indexOf(r.mode)&&function(){if(0!==n._frameQueue.length){for(;n._frameQueue.length;){var e=n._frameQueue.pop();e.onInterrupt&&e.onInterrupt()}t.emit("plotly_animationinterrupted",[])}}(),"reverse"===r.direction&&m.reverse();var k=t._fullLayout._currentFrame;if(k&&r.fromcurrent){var M=-1;for(h=0;h<m.length;h++)if("byname"===(g=m[h]).type&&g.name===k){M=h;break}if(M>0&&M<m.length-1){var T=[];for(h=0;h<m.length;h++)g=m[h],("byname"!==m[h].type||h>M)&&T.push(g);m=T}}m.length>0?function(e){if(0!==e.length){for(var a=0;a<e.length;a++){var o;o="byname"===e[a].type?f.computeFrame(t,e[a].name):e[a].data;var d=s(a),h=l(a);h.duration=Math.min(h.duration,d.duration);var g={frame:o,name:e[a].name,frameOpts:d,transitionOpts:h};a===e.length-1&&(g.onComplete=c(i,2),g.onInterrupt=u),n._frameQueue.push(g)}"immediate"===r.mode&&(n._lastFrameAt=-1/0),n._animationRaf||p()}}(m):(t.emit("plotly_animated"),i())})},r.addFrames=function(t,e,r){if(t=o.getGraphDiv(t),null==e)return Promise.resolve();if(!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t+". It's likely that you've failed to create a plot before adding frames. For more details, see https://plot.ly/javascript/animations/");var n,a,i,l,c=t._transitionData._frames,u=t._transitionData._frameHash;if(!Array.isArray(e))throw new Error("addFrames failure: frameList must be an Array of frame definitions"+e);var d=c.length+2*e.length,p=[],h={};for(n=e.length-1;n>=0;n--)if(o.isPlainObject(e[n])){var g=e[n].name,y=(u[g]||h[g]||{}).name,v=e[n].name,m=u[y]||h[y];y&&v&&"number"==typeof v&&m&&A<5&&(A++,o.warn('addFrames: overwriting frame "'+(u[y]||h[y]).name+'" with a frame whose name of type "number" also equates to "'+y+'". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'),5===A&&o.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed.")),h[g]={name:g},p.push({frame:f.supplyFrameDefaults(e[n]),index:r&&void 0!==r[n]&&null!==r[n]?r[n]:d+n})}p.sort(function(t,e){return t.index>e.index?-1:t.index<e.index?1:0});var x=[],b=[],_=c.length;for(n=p.length-1;n>=0;n--){if("number"==typeof(a=p[n].frame).name&&o.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"),!a.name)for(;u[a.name="frame "+t._transitionData._counter++];);if(u[a.name]){for(i=0;i<c.length&&(c[i]||{}).name!==a.name;i++);x.push({type:"replace",index:i,value:a}),b.unshift({type:"replace",index:i,value:c[i]})}else l=Math.max(0,Math.min(p[n].index,_)),x.push({type:"insert",index:l,value:a}),b.unshift({type:"delete",index:l}),_++}var w=f.modifyFrames,k=f.modifyFrames,M=[t,b],T=[t,x];return s&&s.add(t,w,M,k,T),f.modifyFrames(t,x)},r.deleteFrames=function(t,e){if(t=o.getGraphDiv(t),!o.isPlotDiv(t))throw new Error("This element is not a Plotly plot: "+t);var r,n,a=t._transitionData._frames,i=[],l=[];if(!e)for(e=[],r=0;r<a.length;r++)e.push(r);for((e=e.slice(0)).sort(),r=e.length-1;r>=0;r--)n=e[r],i.push({type:"delete",index:n}),l.unshift({type:"insert",index:n,value:a[n]});var c=f.modifyFrames,u=f.modifyFrames,d=[t,l],p=[t,i];return s&&s.add(t,c,d,u,p),f.modifyFrames(t,i)},r.purge=function(t){var e=(t=o.getGraphDiv(t))._fullLayout||{},r=t._fullData||[],n=t.calcdata||[];return f.cleanPlot([],{},r,e,n),f.purge(t),l.purge(t),e._container&&e._container.remove(),delete t._context,t}},{"../components/color":45,"../components/colorbar/connect":47,"../components/drawing":70,"../constants/xmlns_namespaces":147,"../lib":163,"../lib/events":156,"../lib/queue":177,"../lib/svg_text_utils":184,"../plots/cartesian/axes":207,"../plots/cartesian/constants":212,"../plots/cartesian/graph_interact":216,"../plots/plots":239,"../plots/polar/legacy":242,"../registry":247,"./edit_types":190,"./helpers":191,"./manage_arrays":193,"./plot_config":195,"./plot_schema":196,"./subroutines":198,d3:10,"fast-isnumeric":13,"has-hover":15}],195:[function(t,e,r){"use strict";e.exports={staticPlot:!1,plotlyServerURL:"https://plot.ly",editable:!1,edits:{annotationPosition:!1,annotationTail:!1,annotationText:!1,axisTitleText:!1,colorbarPosition:!1,colorbarTitleText:!1,legendPosition:!1,legendText:!1,shapePosition:!1,titleText:!1},autosizable:!1,queueLength:0,fillFrame:!1,frameMargins:0,scrollZoom:!1,doubleClick:"reset+autosize",showTips:!0,showAxisDragHandles:!0,showAxisRangeEntryBoxes:!0,showLink:!1,sendData:!0,linkText:"Edit chart",showSources:!1,displayModeBar:"hover",modeBarButtonsToRemove:[],modeBarButtonsToAdd:[],modeBarButtons:!1,toImageButtonOptions:{},displaylogo:!0,plotGlPixelRatio:2,setBackground:"transparent",topojsonURL:"https://cdn.plot.ly/",mapboxAccessToken:null,logging:1,globalTransforms:[],locale:"en-US",locales:{}}},{}],196:[function(t,e,r){"use strict";var n=t("../registry"),a=t("../lib"),i=t("../plots/attributes"),o=t("../plots/layout_attributes"),l=t("../plots/frame_attributes"),s=t("../plots/animation_attributes"),c=t("../plots/polar/legacy/area_attributes"),u=t("../plots/polar/legacy/axis_attributes"),f=t("./edit_types"),d=a.extendFlat,p=a.extendDeepAll,h=a.isPlainObject,g="_isSubplotObj",y="_isLinkedToArray",v=[g,y,"_arrayAttrRegexps","_deprecated"];function m(t,e,r){if(!t)return!1;if(t._isLinkedToArray)if(x(e[r]))r++;else if(r<e.length)return!1;for(;r<e.length;r++){var n=t[e[r]];if(!h(n))break;if(t=n,r===e.length-1)break;if(t._isLinkedToArray){if(!x(e[++r]))return!1}else if("info_array"===t.valType){var a=e[++r];if(!x(a))return!1;var i=t.items;if(Array.isArray(i)){if(a>=i.length)return!1;if(2===t.dimensions){if(r++,e.length===r)return t;var o=e[r];if(!x(o))return!1;t=i[a][o]}else t=i[a]}else t=i}}return t}function x(t){return t===Math.round(t)&&t>=0}function b(t){return function(t){r.crawl(t,function(t,e,n){r.isValObject(t)?"data_array"===t.valType?(t.role="data",n[e+"src"]={valType:"string",editType:"none"}):!0===t.arrayOk&&(n[e+"src"]={valType:"string",editType:"none"}):h(t)&&(t.role="object")})}(t),function(t){r.crawl(t,function(t,e,r){if(!t)return;var n=t[y];if(!n)return;delete t[y],r[e]={items:{}},r[e].items[n]=t,r[e].role="object"})}(t),function(t){!function t(e){for(var r in e)if(h(e[r]))t(e[r]);else if(Array.isArray(e[r]))for(var n=0;n<e[r].length;n++)t(e[r][n]);else e[r]instanceof RegExp&&(e[r]=e[r].toString())}(t)}(t),t}function _(t,e,r){var n=a.nestedProperty(t,r),i=p({},e.layoutAttributes);i[g]=!0,n.set(i)}function w(t,e,r){var n=a.nestedProperty(t,r);n.set(p(n.get()||{},e))}r.IS_SUBPLOT_OBJ=g,r.IS_LINKED_TO_ARRAY=y,r.DEPRECATED="_deprecated",r.UNDERSCORE_ATTRS=v,r.get=function(){var t={};n.allTypes.concat("area").forEach(function(e){t[e]=function(t){var e,r;"area"===t?(e={attributes:c},r={}):(e=n.modules[t]._module,r=e.basePlotModule);var a={type:null};p(a,i),p(a,e.attributes),r.attributes&&p(a,r.attributes);a.type=t;var o={meta:e.meta||{},attributes:b(a)};if(e.layoutAttributes){var l={};p(l,e.layoutAttributes),o.layoutAttributes=b(l)}return o}(e)});var e,r={};return Object.keys(n.transformsRegistry).forEach(function(t){r[t]=function(t){var e=n.transformsRegistry[t],r=p({},e.attributes);return Object.keys(n.componentsRegistry).forEach(function(e){var a=n.componentsRegistry[e];a.schema&&a.schema.transforms&&a.schema.transforms[t]&&Object.keys(a.schema.transforms[t]).forEach(function(e){w(r,a.schema.transforms[t][e],e)})}),{attributes:b(r)}}(t)}),{defs:{valObjects:a.valObjectMeta,metaKeys:v.concat(["description","role","editType","impliedEdits"]),editType:{traces:f.traces,layout:f.layout},impliedEdits:{}},traces:t,layout:function(){var t,e,r={};for(t in p(r,o),n.subplotsRegistry)if((e=n.subplotsRegistry[t]).layoutAttributes)if(Array.isArray(e.attr))for(var a=0;a<e.attr.length;a++)_(r,e,e.attr[a]);else{var i="subplot"===e.attr?e.name:e.attr;_(r,e,i)}for(t in r=function(t){return d(t,{radialaxis:u.radialaxis,angularaxis:u.angularaxis}),d(t,u.layout),t}(r),n.componentsRegistry){var l=(e=n.componentsRegistry[t]).schema;if(l&&(l.subplots||l.layout)){var s=l.subplots;if(s&&s.xaxis&&!s.yaxis)for(var c in s.xaxis)delete r.yaxis[c]}else e.layoutAttributes&&w(r,e.layoutAttributes,e.name)}return{layoutAttributes:b(r)}}(),transforms:r,frames:(e={frames:a.extendDeepAll({},l)},b(e),e.frames),animation:b(s)}},r.crawl=function(t,e,n,a){var i=n||0;a=a||"",Object.keys(t).forEach(function(n){var o=t[n];if(-1===v.indexOf(n)){var l=(a?a+".":"")+n;e(o,n,t,i,l),r.isValObject(o)||h(o)&&"impliedEdits"!==n&&r.crawl(o,e,i+1,l)}})},r.isValObject=function(t){return t&&void 0!==t.valType},r.findArrayAttributes=function(t){var e,n,o=[],l=[],s=[];function c(t,r,i,c){l=l.slice(0,c).concat([r]),s=s.slice(0,c).concat([t&&t._isLinkedToArray]),t&&("data_array"===t.valType||!0===t.arrayOk)&&!("colorbar"===l[c-1]&&("ticktext"===r||"tickvals"===r))&&function t(e,r,i){var c=e[l[r]];var u=i+l[r];if(r===l.length-1)a.isArrayOrTypedArray(c)&&o.push(n+u);else if(s[r]){if(Array.isArray(c))for(var f=0;f<c.length;f++)a.isPlainObject(c[f])&&t(c[f],r+1,u+"["+f+"].")}else a.isPlainObject(c)&&t(c,r+1,u+".")}(e,0,"")}e=t,n="",r.crawl(i,c),t._module&&t._module.attributes&&r.crawl(t._module.attributes,c);var u=t.transforms;if(u)for(var f=0;f<u.length;f++){var d=u[f],p=d._module;p&&(n="transforms["+f+"].",e=d,r.crawl(p.attributes,c))}return o},r.getTraceValObject=function(t,e){var r,a,o=e[0],l=1;if("transforms"===o){if(1===e.length)return i.transforms;var s=t.transforms;if(!Array.isArray(s)||!s.length)return!1;var u=e[1];if(!x(u)||u>=s.length)return!1;a=(r=(n.transformsRegistry[s[u].type]||{}).attributes)&&r[e[2]],l=3}else if("area"===t.type)a=c[o];else{var f=t._module;if(f||(f=(n.modules[t.type||i.type.dflt]||{})._module),!f)return!1;if(!(a=(r=f.attributes)&&r[o])){var d=f.basePlotModule;d&&d.attributes&&(a=d.attributes[o])}a||(a=i[o])}return m(a,e,l)},r.getLayoutValObject=function(t,e){return m(function(t,e){var r,a,i,l,s=t._basePlotModules;if(s){var c;for(r=0;r<s.length;r++){if((i=s[r]).attrRegex&&i.attrRegex.test(e)){if(i.layoutAttrOverrides)return i.layoutAttrOverrides;!c&&i.layoutAttributes&&(c=i.layoutAttributes)}var f=i.baseLayoutAttrOverrides;if(f&&e in f)return f[e]}if(c)return c}var d=t._modules;if(d)for(r=0;r<d.length;r++)if((l=d[r].layoutAttributes)&&e in l)return l[e];for(a in n.componentsRegistry)if(!(i=n.componentsRegistry[a]).schema&&e===i.name)return i.layoutAttributes;if(e in o)return o[e];if("radialaxis"===e||"angularaxis"===e)return u[e];return u.layout[e]||!1}(t,e[0]),e,1)}},{"../lib":163,"../plots/animation_attributes":202,"../plots/attributes":204,"../plots/frame_attributes":234,"../plots/layout_attributes":237,"../plots/polar/legacy/area_attributes":240,"../plots/polar/legacy/axis_attributes":241,"../registry":247,"./edit_types":190}],197:[function(t,e,r){"use strict";var n=t("../lib"),a=t("../plots/attributes"),i="templateitemname",o={name:{valType:"string",editType:"none"}};function l(t){return t&&"string"==typeof t}function s(t){var e=t.length-1;return"s"!==t.charAt(e)&&n.warn("bad argument to arrayDefaultKey: "+t),t.substr(0,t.length-1)+"defaults"}o[i]={valType:"string",editType:"calc"},r.templatedArray=function(t,e){return e._isLinkedToArray=t,e.name=o.name,e[i]=o[i],e},r.traceTemplater=function(t){var e,r,i={};for(e in t)r=t[e],Array.isArray(r)&&r.length&&(i[e]=0);return{newTrace:function(o){var l={type:e=n.coerce(o,{},a,"type"),_template:null};if(e in i){r=t[e];var s=i[e]%r.length;i[e]++,l._template=r[s]}return l}}},r.newContainer=function(t,e,r){var a=t._template,i=a&&(a[e]||r&&a[r]);return n.isPlainObject(i)||(i=null),t[e]={_template:i}},r.arrayTemplater=function(t,e,r){var n=t._template,a=n&&n[s(e)],o=n&&n[e];Array.isArray(o)&&o.length||(o=[]);var c={};return{newItem:function(t){var e={name:t.name,_input:t},n=e[i]=t[i];if(!l(n))return e._template=a,e;for(var s=0;s<o.length;s++){var u=o[s];if(u.name===n)return c[n]=1,e._template=u,e}return e[r]=t[r]||!1,e._template=!1,e},defaultItems:function(){for(var t=[],e=0;e<o.length;e++){var r=o[e],n=r.name;if(l(n)&&!c[n]){var a={_template:r,name:n,_input:{_templateitemname:n}};a[i]=r[i],t.push(a),c[n]=1}}return t}}},r.arrayDefaultKey=s,r.arrayEditor=function(t,e,r){var a=(n.nestedProperty(t,e).get()||[]).length,o=r._index,l=o>=a&&(r._input||{})._templateitemname;l&&(o=a);var s,c=e+"["+o+"]";function u(){s={},l&&(s[c]={},s[c][i]=l)}function f(t,e){l?n.nestedProperty(s[c],t).set(e):s[c+"."+t]=e}function d(){var t=s;return u(),t}return u(),{modifyBase:function(t,e){s[t]=e},modifyItem:f,getUpdateObj:d,applyUpdate:function(e,r){e&&f(e,r);var a=d();for(var i in a)n.nestedProperty(t,i).set(a[i])}}}},{"../lib":163,"../plots/attributes":204}],198:[function(t,e,r){"use strict";var n=t("d3"),a=t("../registry"),i=t("../plots/plots"),o=t("../lib"),l=t("../lib/clear_gl_canvases"),s=t("../components/color"),c=t("../components/drawing"),u=t("../components/titles"),f=t("../components/modebar"),d=t("../plots/cartesian/axes"),p=t("../constants/alignment"),h=t("../plots/cartesian/constraints"),g=h.enforce,y=h.clean,v=t("../plots/cartesian/autorange").doAutoRange;function m(t){var e,a=t._fullLayout,i=a._size,l=i.p,u=d.list(t,"",!0),h=a._has("cartesian");function g(t,e,r){var n=t._lw/2;return"x"===t._id.charAt(0)?e?"top"===r?e._offset-l-n:e._offset+e._length+l+n:i.t+i.h*(1-(t.position||0))+n%1:e?"right"===r?e._offset+e._length+l+n:e._offset-l-n:i.l+i.w*(t.position||0)+n%1}for(e=0;e<u.length;e++){var y=u[e];y.setScale();var v=y._anchorAxis;y._linepositions={},y._lw=c.crispRound(t,y.linewidth,1),y._mainLinePosition=g(y,v,y.side),y._mainMirrorPosition=y.mirror&&v?g(y,v,p.OPPOSITE_SIDE[y.side]):null,y._mainSubplot=x(y,a)}a._paperdiv.style({width:a.width+"px",height:a.height+"px"}).selectAll(".main-svg").call(c.setSize,a.width,a.height),t._context.setBackground(t,a.paper_bgcolor);var m=a._paper.selectAll("g.subplot"),_=[],k=[];m.each(function(t){var e=a._plots[t];if(e.mainplot)return e.bg&&e.bg.remove(),void(e.bg=void 0);var r=e.xaxis.domain,n=e.yaxis.domain,i=e.plotgroup;if(function(t,e,r){for(var n=0;n<r.length;n++){var a=r[n][0],i=r[n][1];if(!(a[0]>=t[1]||a[1]<=t[0])&&i[0]<e[1]&&i[1]>e[0])return!0}return!1}(r,n,k)){var l=i.node(),s=e.bg=o.ensureSingle(i,"rect","bg");l.insertBefore(s.node(),l.childNodes[0])}else i.select("rect.bg").remove(),_.push(t),k.push([r,n])});var M=a._bgLayer.selectAll(".bg").data(_);return M.enter().append("rect").classed("bg",!0),M.exit().remove(),M.each(function(t){a._plots[t].bg=n.select(this)}),m.each(function(t){var e=a._plots[t],r=e.xaxis,n=e.yaxis;e.bg&&h&&e.bg.call(c.setRect,r._offset-l,n._offset-l,r._length+2*l,n._length+2*l).call(s.fill,a.plot_bgcolor).style("stroke-width",0);var i,f,d=e.clipId="clip"+a._uid+t+"plot",p=o.ensureSingleById(a._clips,"clipPath",d,function(t){t.classed("plotclip",!0).append("rect")});if(e.clipRect=p.select("rect").attr({width:r._length,height:n._length}),c.setTranslate(e.plot,r._offset,n._offset),e._hasClipOnAxisFalse?(i=null,f=d):(i=d,f=null),c.setClipUrl(e.plot,i),e.layerClipId=f,h){var y,v,m,x,_,k,M,T,A,L,C,S,O,P="M0,0";b(r,t)&&(_=w(r,"left",n,u),y=r._offset-(_?l+_:0),k=w(r,"right",n,u),v=r._offset+r._length+(k?l+k:0),m=g(r,n,"bottom"),x=g(r,n,"top"),(O=!r._anchorAxis||t!==r._mainSubplot)&&r.ticks&&"allticks"===r.mirror&&(r._linepositions[t]=[m,x]),P=I(r,z,function(t){return"M"+r._offset+","+t+"h"+r._length}),O&&r.showline&&("all"===r.mirror||"allticks"===r.mirror)&&(P+=z(m)+z(x)),e.xlines.style("stroke-width",r._lw+"px").call(s.stroke,r.showline?r.linecolor:"rgba(0,0,0,0)")),e.xlines.attr("d",P);var D="M0,0";b(n,t)&&(C=w(n,"bottom",r,u),M=n._offset+n._length+(C?l:0),S=w(n,"top",r,u),T=n._offset-(S?l:0),A=g(n,r,"left"),L=g(n,r,"right"),(O=!n._anchorAxis||t!==r._mainSubplot)&&n.ticks&&"allticks"===n.mirror&&(n._linepositions[t]=[A,L]),D=I(n,E,function(t){return"M"+t+","+n._offset+"v"+n._length}),O&&n.showline&&("all"===n.mirror||"allticks"===n.mirror)&&(D+=E(A)+E(L)),e.ylines.style("stroke-width",n._lw+"px").call(s.stroke,n.showline?n.linecolor:"rgba(0,0,0,0)")),e.ylines.attr("d",D)}function z(t){return"M"+y+","+t+"H"+v}function E(t){return"M"+t+","+T+"V"+M}function I(e,r,n){if(!e.showline||t!==e._mainSubplot)return"";if(!e._anchorAxis)return n(e._mainLinePosition);var a=r(e._mainLinePosition);return e.mirror&&(a+=r(e._mainMirrorPosition)),a}}),d.makeClipPaths(t),r.drawMainTitle(t),f.manage(t),t._promises.length&&Promise.all(t._promises)}function x(t,e){var r=e._subplots,n=r.cartesian.concat(r.gl2d||[]),a={_fullLayout:e},i="x"===t._id.charAt(0),o=t._mainAxis._anchorAxis,l="",s="",c="";if(o&&(c=o._mainAxis._id,l=i?t._id+c:c+t._id),!l||!e._plots[l]){l="";for(var u=0;u<n.length;u++){var f=n[u],p=f.indexOf("y"),h=i?f.substr(0,p):f.substr(p),g=i?f.substr(p):f.substr(0,p);if(h===t._id){s||(s=f);var y=d.getFromId(a,g);if(c&&y.overlaying===c){l=f;break}}}}return l||s}function b(t,e){return(t.ticks||t.showline)&&(e===t._mainSubplot||"all"===t.mirror||"allticks"===t.mirror)}function _(t,e,r){if(!r.showline||!r._lw)return!1;if("all"===r.mirror||"allticks"===r.mirror)return!0;var n=r._anchorAxis;if(!n)return!1;var a=p.FROM_BL[e];return r.side===e?n.domain[a]===t.domain[a]:r.mirror&&n.domain[1-a]===t.domain[1-a]}function w(t,e,r,n){if(_(t,e,r))return r._lw;for(var a=0;a<n.length;a++){var i=n[a];if(i._mainAxis===r._mainAxis&&_(t,e,i))return i._lw}return 0}r.layoutStyles=function(t){return o.syncOrAsync([i.doAutoMargin,m],t)},r.drawMainTitle=function(t){var e=t._fullLayout;u.draw(t,"gtitle",{propContainer:e,propName:"title",placeholder:e._dfltTitle.plot,attributes:{x:e.width/2,y:e._size.t/2,"text-anchor":"middle"}})},r.doTraceStyle=function(t){for(var e=0;e<t.calcdata.length;e++){var r=t.calcdata[e],n=(((r[0]||{}).trace||{})._module||{}).arraysToCalcdata;n&&n(r,r[0].trace)}return i.style(t),a.getComponentMethod("legend","draw")(t),i.previousPromises(t)},r.doColorBars=function(t){for(var e=0;e<t.calcdata.length;e++){var r=t.calcdata[e][0];if((r.t||{}).cb){var n=r.trace,o=r.t.cb;a.traceIs(n,"contour")&&o.line({width:!1!==n.contours.showlines?n.line.width:0,dash:n.line.dash,color:"line"===n.contours.coloring?o._opts.line.color:n.line.color});var l=n._module.colorbar.container,s=(l?n[l]:n).colorbar;o.options(s)()}}return i.previousPromises(t)},r.layoutReplot=function(t){var e=t.layout;return t.layout=void 0,a.call("plot",t,"",e)},r.doLegend=function(t){return a.getComponentMethod("legend","draw")(t),i.previousPromises(t)},r.doTicksRelayout=function(t,e){return e?d.doTicks(t,Object.keys(e),!0):d.doTicks(t,"redraw"),t._fullLayout._hasOnlyLargeSploms&&(l(t),a.subplotsRegistry.splom.plot(t)),r.drawMainTitle(t),i.previousPromises(t)},r.doModeBar=function(t){var e=t._fullLayout;f.manage(t);for(var r=0;r<e._basePlotModules.length;r++){var n=e._basePlotModules[r].updateFx;n&&n(e)}return i.previousPromises(t)},r.doCamera=function(t){for(var e=t._fullLayout,r=e._subplots.gl3d,n=0;n<r.length;n++){var a=e[r[n]];a._scene.setCamera(a.camera)}},r.drawData=function(t){var e,r=t._fullLayout,n=t.calcdata;for(e=0;e<n.length;e++){var o=n[e][0].trace;!0===o.visible&&o._module.colorbar||r._infolayer.select(".cb"+o.uid).remove()}l(t);var s=r._basePlotModules;for(e=0;e<s.length;e++)s[e].plot(t);return i.style(t),a.getComponentMethod("shapes","draw")(t),a.getComponentMethod("annotations","draw")(t),r._replotting=!1,i.previousPromises(t)},r.doAutoRangeAndConstraints=function(t){for(var e=d.list(t,"",!0),r=0;r<e.length;r++){var n=e[r];y(t,n),v(n)}g(t)},r.finalDraw=function(t){a.getComponentMethod("shapes","draw")(t),a.getComponentMethod("images","draw")(t),a.getComponentMethod("annotations","draw")(t),a.getComponentMethod("rangeslider","draw")(t),a.getComponentMethod("rangeselector","draw")(t)},r.drawMarginPushers=function(t){a.getComponentMethod("legend","draw")(t),a.getComponentMethod("rangeselector","draw")(t),a.getComponentMethod("sliders","draw")(t),a.getComponentMethod("updatemenus","draw")(t)}},{"../components/color":45,"../components/drawing":70,"../components/modebar":108,"../components/titles":136,"../constants/alignment":143,"../lib":163,"../lib/clear_gl_canvases":152,"../plots/cartesian/autorange":206,"../plots/cartesian/axes":207,"../plots/cartesian/constraints":214,"../plots/plots":239,"../registry":247,d3:10}],199:[function(t,e,r){"use strict";var n=t("../lib"),a=n.isPlainObject,i=t("./plot_schema"),o=t("../plots/plots"),l=t("../plots/attributes"),s=t("./plot_template"),c=t("./plot_config");function u(t,e){t=n.extendDeep({},t);var r,i,o=Object.keys(t).sort();function l(e,r,n){if(a(r)&&a(e))u(e,r);else if(Array.isArray(r)&&Array.isArray(e)){var o=s.arrayTemplater({_template:t},n);for(i=0;i<r.length;i++){var l=r[i],c=o.newItem(l)._template;c&&u(c,l)}var f=o.defaultItems();for(i=0;i<f.length;i++)r.push(f[i]._template);for(i=0;i<r.length;i++)delete r[i].templateitemname}}for(r=0;r<o.length;r++){var c=o[r],d=t[c];if(c in e?l(d,e[c],c):e[c]=d,f(c)===c)for(var p in e){var h=f(p);p===h||h!==c||p in t||l(d,e[p],c)}}}function f(t){return t.replace(/[0-9]+$/,"")}function d(t,e,r,i,o){var l=o&&r(o);for(var c in t){var u=t[c],h=p(t,c,i),g=p(t,c,o),y=r(g);if(!y){var v=f(c);v!==c&&(y=r(g=p(t,v,o)))}if((!l||l!==y)&&!(!y||y._noTemplating||"data_array"===y.valType||y.arrayOk&&Array.isArray(u)))if(!y.valType&&a(u))d(u,e,r,h,g);else if(y._isLinkedToArray&&Array.isArray(u))for(var m=!1,x=0,b={},_=0;_<u.length;_++){var w=u[_];if(a(w)){var k=w.name;if(k)b[k]||(d(w,e,r,p(u,x,h),p(u,x,g)),x++,b[k]=1);else if(!m){var M=p(t,s.arrayDefaultKey(c),i),T=p(u,x,h);d(w,e,r,T,p(u,x,g));var A=n.nestedProperty(e,T);n.nestedProperty(e,M).set(A.get()),A.set(null),m=!0}}}else{n.nestedProperty(e,h).set(u)}}}function p(t,e,r){return r?Array.isArray(t)?r+"["+e+"]":r+"."+e:e}function h(t){for(var e=0;e<t.length;e++)if(a(t[e]))return!0}function g(t){var e;switch(t.code){case"data":e="The template has no key data.";break;case"layout":e="The template has no key layout.";break;case"missing":e=t.path?"There are no templates for item "+t.path+" with name "+t.templateitemname:"There are no templates for trace "+t.index+", of type "+t.traceType+".";break;case"unused":e=t.path?"The template item at "+t.path+" was not used in constructing the plot.":t.dataCount?"Some of the templates of type "+t.traceType+" were not used. The template has "+t.templateCount+" traces, the data only has "+t.dataCount+" of this type.":"The template has "+t.templateCount+" traces of type "+t.traceType+" but there are none in the data.";break;case"reused":e="Some of the templates of type "+t.traceType+" were used more than once. The template has "+t.templateCount+" traces, the data has "+t.dataCount+" of this type."}return t.msg=e,t}r.makeTemplate=function(t){t=n.extendDeep({_context:c},t),o.supplyDefaults(t);var e=t.data||[],r=t.layout||{};r._basePlotModules=t._fullLayout._basePlotModules,r._modules=t._fullLayout._modules;var s={data:{},layout:{}};e.forEach(function(t){var e={};d(t,e,function(t,e){return i.getTraceValObject(t,n.nestedProperty({},e).parts)}.bind(null,t));var r=n.coerce(t,{},l,"type"),a=s.data[r];a||(a=s.data[r]=[]),a.push(e)}),d(r,s.layout,function(t,e){return i.getLayoutValObject(t,n.nestedProperty({},e).parts)}.bind(null,r)),delete s.layout.template;var f=r.template;if(a(f)){var p,h,g,y,v,m,x=f.layout;a(x)&&u(x,s.layout);var b=f.data;if(a(b)){for(h in s.data)if(g=b[h],Array.isArray(g)){for(m=(v=s.data[h]).length,y=g.length,p=0;p<m;p++)u(g[p%y],v[p]);for(p=m;p<y;p++)v.push(n.extendDeep({},g[p]))}for(h in b)h in s.data||(s.data[h]=n.extendDeep([],b[h]))}}return s},r.validateTemplate=function(t,e){var r=n.extendDeep({},{_context:c,data:t.data,layout:t.layout}),i=r.layout||{};a(e)||(e=i.template||{});var l=e.layout,s=e.data,u=[];r.layout=i,r.layout.template=e,o.supplyDefaults(r);var d=r._fullLayout,y=r._fullData,v={};if(a(l)?(!function t(e,r){for(var n in e)if("_"!==n.charAt(0)&&a(e[n])){var i,o=f(n),l=[];for(i=0;i<r.length;i++)l.push(p(e,n,r[i])),o!==n&&l.push(p(e,o,r[i]));for(i=0;i<l.length;i++)v[l[i]]=1;t(e[n],l)}}(d,["layout"]),function t(e,r){for(var n in e)if(-1===n.indexOf("defaults")&&a(e[n])){var i=p(e,n,r);v[i]?t(e[n],i):u.push({code:"unused",path:i})}}(l,"layout")):u.push({code:"layout"}),a(s)){for(var m,x={},b=0;b<y.length;b++){var _=y[b];x[m=_.type]=(x[m]||0)+1,_._fullInput._template||u.push({code:"missing",index:_._fullInput.index,traceType:m})}for(m in s){var w=s[m].length,k=x[m]||0;w>k?u.push({code:"unused",traceType:m,templateCount:w,dataCount:k}):k>w&&u.push({code:"reused",traceType:m,templateCount:w,dataCount:k})}}else u.push({code:"data"});if(function t(e,r){for(var n in e)if("_"!==n.charAt(0)){var i=e[n],o=p(e,n,r);a(i)?(Array.isArray(e)&&!1===i._template&&i.templateitemname&&u.push({code:"missing",path:o,templateitemname:i.templateitemname}),t(i,o)):Array.isArray(i)&&h(i)&&t(i,o)}}({data:y,layout:d},""),u.length)return u.map(g)}},{"../lib":163,"../plots/attributes":204,"../plots/plots":239,"./plot_config":195,"./plot_schema":196,"./plot_template":197}],200:[function(t,e,r){"use strict";var n=t("./plot_api"),a=t("../lib"),i=t("../snapshot/helpers"),o=t("../snapshot/tosvg"),l=t("../snapshot/svgtoimg"),s={format:{valType:"enumerated",values:["png","jpeg","webp","svg"],dflt:"png"},width:{valType:"number",min:1},height:{valType:"number",min:1},scale:{valType:"number",min:0,dflt:1},setBackground:{valType:"any",dflt:!1},imageDataOnly:{valType:"boolean",dflt:!1}},c=/^data:image\/\w+;base64,/;e.exports=function(t,e){var r,u,f;function d(t){return!(t in e)||a.validate(e[t],s[t])}if(e=e||{},a.isPlainObject(t)?(r=t.data||[],u=t.layout||{},f=t.config||{}):(t=a.getGraphDiv(t),r=a.extendDeep([],t.data),u=a.extendDeep({},t.layout),f=t._context),!d("width")||!d("height"))throw new Error("Height and width should be pixel values.");if(!d("format"))throw new Error("Image format is not jpeg, png, svg or webp.");var p={};function h(t,r){return a.coerce(e,p,s,t,r)}var g=h("format"),y=h("width"),v=h("height"),m=h("scale"),x=h("setBackground"),b=h("imageDataOnly"),_=document.createElement("div");_.style.position="absolute",_.style.left="-5000px",document.body.appendChild(_);var w=a.extendFlat({},u);y&&(w.width=y),v&&(w.height=v);var k=a.extendFlat({},f,{staticPlot:!0,setBackground:x}),M=i.getRedrawFunc(_);function T(){return new Promise(function(t){setTimeout(t,i.getDelay(_._fullLayout))})}function A(){return new Promise(function(t,e){var r=o(_,g,m),i=_._fullLayout.width,s=_._fullLayout.height;if(n.purge(_),document.body.removeChild(_),"svg"===g)return t(b?r:"data:image/svg+xml,"+encodeURIComponent(r));var c=document.createElement("canvas");c.id=a.randstr(),l({format:g,width:i,height:s,scale:m,canvas:c,svg:r,promise:!0}).then(t).catch(e)})}return new Promise(function(t,e){n.plot(_,r,w,k).then(M).then(T).then(A).then(function(e){t(function(t){return b?t.replace(c,""):t}(e))}).catch(function(t){e(t)})})}},{"../lib":163,"../snapshot/helpers":251,"../snapshot/svgtoimg":253,"../snapshot/tosvg":255,"./plot_api":194}],201:[function(t,e,r){"use strict";var n=t("../lib"),a=t("../plots/plots"),i=t("./plot_schema"),o=t("./plot_config"),l=n.isPlainObject,s=Array.isArray,c=n.isArrayOrTypedArray;function u(t,e,r,a,i,o){o=o||[];for(var f=Object.keys(t),d=0;d<f.length;d++){var y=f[d];if("transforms"!==y){var v=o.slice();v.push(y);var m=t[y],x=e[y],b=g(r,y),_="info_array"===(b||{}).valType,w="colorscale"===(b||{}).valType,k=(b||{}).items;if(h(r,y))if(l(m)&&l(x))u(m,x,b,a,i,v);else if(_&&s(m)){m.length>x.length&&a.push(p("unused",i,v.concat(x.length)));var M,T,A,L,C,S=x.length,O=Array.isArray(k);if(O&&(S=Math.min(S,k.length)),2===b.dimensions)for(T=0;T<S;T++)if(s(m[T])){m[T].length>x[T].length&&a.push(p("unused",i,v.concat(T,x[T].length)));var P=x[T].length;for(M=0;M<(O?Math.min(P,k[T].length):P);M++)A=O?k[T][M]:k,L=m[T][M],C=x[T][M],n.validate(L,A)?C!==L&&C!==+L&&a.push(p("dynamic",i,v.concat(T,M),L,C)):a.push(p("value",i,v.concat(T,M),L))}else a.push(p("array",i,v.concat(T),m[T]));else for(T=0;T<S;T++)A=O?k[T]:k,L=m[T],C=x[T],n.validate(L,A)?C!==L&&C!==+L&&a.push(p("dynamic",i,v.concat(T),L,C)):a.push(p("value",i,v.concat(T),L))}else if(b.items&&!_&&s(m)){var D,z,E=k[Object.keys(k)[0]],I=[];for(D=0;D<x.length;D++){var N=x[D]._index||D;if((z=v.slice()).push(N),l(m[N])&&l(x[D])){I.push(N);var R=m[N],F=x[D];l(R)&&!1!==R.visible&&!1===F.visible?a.push(p("invisible",i,z)):u(R,F,E,a,i,z)}}for(D=0;D<m.length;D++)(z=v.slice()).push(D),l(m[D])?-1===I.indexOf(D)&&a.push(p("unused",i,z)):a.push(p("object",i,z,m[D]))}else!l(m)&&l(x)?a.push(p("object",i,v,m)):c(m)||!c(x)||_||w?y in e?n.validate(m,b)?"enumerated"===b.valType&&(b.coerceNumber&&m!==+x||m!==x)&&a.push(p("dynamic",i,v,m,x)):a.push(p("value",i,v,m)):a.push(p("unused",i,v,m)):a.push(p("array",i,v,m));else a.push(p("schema",i,v))}}return a}e.exports=function(t,e){var r,c,f=i.get(),d=[],h={_context:n.extendFlat({},o)};s(t)?(h.data=n.extendDeep([],t),r=t):(h.data=[],r=[],d.push(p("array","data"))),l(e)?(h.layout=n.extendDeep({},e),c=e):(h.layout={},c={},arguments.length>1&&d.push(p("object","layout"))),a.supplyDefaults(h);for(var g=h._fullData,y=r.length,v=0;v<y;v++){var m=r[v],x=["data",v];if(l(m)){var b=g[v],_=b.type,w=f.traces[_].attributes;w.type={valType:"enumerated",values:[_]},!1===b.visible&&!1!==m.visible&&d.push(p("invisible",x)),u(m,b,w,d,x);var k=m.transforms,M=b.transforms;if(k){s(k)||d.push(p("array",x,["transforms"])),x.push("transforms");for(var T=0;T<k.length;T++){var A=["transforms",T],L=k[T].type;if(l(k[T])){var C=f.transforms[L]?f.transforms[L].attributes:{};C.type={valType:"enumerated",values:Object.keys(f.transforms)},u(k[T],M[T],C,d,x,A)}else d.push(p("object",x,A))}}}else d.push(p("object",x))}return u(c,h._fullLayout,function(t,e){for(var r=0;r<e.length;r++){var a=e[r].type,i=t.traces[a].layoutAttributes;i&&n.extendFlat(t.layout.layoutAttributes,i)}return t.layout.layoutAttributes}(f,g),d,"layout"),0===d.length?void 0:d};var f={object:function(t,e){return("layout"===t&&""===e?"The layout argument":"data"===t[0]&&""===e?"Trace "+t[1]+" in the data argument":d(t)+"key "+e)+" must be linked to an object container"},array:function(t,e){return("data"===t?"The data argument":d(t)+"key "+e)+" must be linked to an array container"},schema:function(t,e){return d(t)+"key "+e+" is not part of the schema"},unused:function(t,e,r){var n=l(r)?"container":"key";return d(t)+n+" "+e+" did not get coerced"},dynamic:function(t,e,r,n){return[d(t)+"key",e,"(set to '"+r+"')","got reset to","'"+n+"'","during defaults."].join(" ")},invisible:function(t,e){return(e?d(t)+"item "+e:"Trace "+t[1])+" got defaulted to be not visible"},value:function(t,e,r){return[d(t)+"key "+e,"is set to an invalid value ("+r+")"].join(" ")}};function d(t){return s(t)?"In data trace "+t[1]+", ":"In "+t+", "}function p(t,e,r,a,i){var o,l;r=r||"",s(e)?(o=e[0],l=e[1]):(o=e,l=null);var c=function(t){if(!s(t))return String(t);for(var e="",r=0;r<t.length;r++){var n=t[r];"number"==typeof n?e=e.substr(0,e.length-1)+"["+n+"]":e+=n,r<t.length-1&&(e+=".")}return e}(r),u=f[t](e,c,a,i);return n.log(u),{code:t,container:o,trace:l,path:r,astr:c,msg:u}}function h(t,e){var r=v(e),n=r.keyMinusId,a=r.id;return!!(n in t&&t[n]._isSubplotObj&&a)||e in t}function g(t,e){return e in t?t[e]:t[v(e).keyMinusId]}var y=n.counterRegex("([a-z]+)");function v(t){var e=t.match(y);return{keyMinusId:e&&e[1],id:e&&e[2]}}},{"../lib":163,"../plots/plots":239,"./plot_config":195,"./plot_schema":196}],202:[function(t,e,r){"use strict";e.exports={mode:{valType:"enumerated",dflt:"afterall",values:["immediate","next","afterall"]},direction:{valType:"enumerated",values:["forward","reverse"],dflt:"forward"},fromcurrent:{valType:"boolean",dflt:!1},frame:{duration:{valType:"number",min:0,dflt:500},redraw:{valType:"boolean",dflt:!0}},transition:{duration:{valType:"number",min:0,dflt:500},easing:{valType:"enumerated",dflt:"cubic-in-out",values:["linear","quad","cubic","sin","exp","circle","elastic","back","bounce","linear-in","quad-in","cubic-in","sin-in","exp-in","circle-in","elastic-in","back-in","bounce-in","linear-out","quad-out","cubic-out","sin-out","exp-out","circle-out","elastic-out","back-out","bounce-out","linear-in-out","quad-in-out","cubic-in-out","sin-in-out","exp-in-out","circle-in-out","elastic-in-out","back-in-out","bounce-in-out"]}}}},{}],203:[function(t,e,r){"use strict";var n=t("../lib"),a=t("../plot_api/plot_template");e.exports=function(t,e,r){var i,o,l=r.name,s=r.inclusionAttr||"visible",c=e[l],u=n.isArrayOrTypedArray(t[l])?t[l]:[],f=e[l]=[],d=a.arrayTemplater(e,l,s);for(i=0;i<u.length;i++){var p=u[i];n.isPlainObject(p)?o=d.newItem(p):(o=d.newItem({}))[s]=!1,o._index=i,!1!==o[s]&&r.handleItemDefaults(p,o,e,r),f.push(o)}var h=d.defaultItems();for(i=0;i<h.length;i++)(o=h[i])._index=f.length,r.handleItemDefaults({},o,e,r,{}),f.push(o);if(n.isArrayOrTypedArray(c)){var g=Math.min(c.length,f.length);for(i=0;i<g;i++)n.relinkPrivateKeys(f[i],c[i])}return f}},{"../lib":163,"../plot_api/plot_template":197}],204:[function(t,e,r){"use strict";var n=t("../components/fx/attributes");e.exports={type:{valType:"enumerated",values:[],dflt:"scatter",editType:"calc+clearAxisTypes",_noTemplating:!0},visible:{valType:"enumerated",values:[!0,!1,"legendonly"],dflt:!0,editType:"calc"},showlegend:{valType:"boolean",dflt:!0,editType:"style"},legendgroup:{valType:"string",dflt:"",editType:"style"},opacity:{valType:"number",min:0,max:1,dflt:1,editType:"style"},name:{valType:"string",editType:"style"},uid:{valType:"string",editType:"plot"},ids:{valType:"data_array",editType:"calc"},customdata:{valType:"data_array",editType:"calc"},selectedpoints:{valType:"any",editType:"calc"},hoverinfo:{valType:"flaglist",flags:["x","y","z","text","name"],extras:["all","none","skip"],arrayOk:!0,dflt:"all",editType:"none"},hoverlabel:n.hoverlabel,stream:{token:{valType:"string",noBlank:!0,strict:!0,editType:"calc"},maxpoints:{valType:"number",min:0,max:1e4,dflt:500,editType:"calc"},editType:"calc"},transforms:{_isLinkedToArray:"transform",editType:"calc"}}},{"../components/fx/attributes":79}],205:[function(t,e,r){"use strict";e.exports={xaxis:{valType:"subplotid",dflt:"x",editType:"calc+clearAxisTypes"},yaxis:{valType:"subplotid",dflt:"y",editType:"calc+clearAxisTypes"}}},{}],206:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../../constants/numerical").FP_SAFE;function o(t){var e,r,n,i,o,s,c,u,f=[],d=t._min[0].val,p=t._max[0].val,h=0,g=!1,y=l(t);for(e=1;e<t._min.length&&d===p;e++)d=Math.min(d,t._min[e].val);for(e=1;e<t._max.length&&d===p;e++)p=Math.max(p,t._max[e].val);if(t.range){var v=a.simpleMap(t.range,t.r2l);g=v[1]<v[0]}for("reversed"===t.autorange&&(g=!0,t.autorange=!0),e=0;e<t._min.length;e++)for(n=t._min[e],r=0;r<t._max.length;r++)u=(i=t._max[r]).val-n.val,c=t._length-y(n)-y(i),u>0&&c>0&&u/c>h&&(o=n,s=i,h=u/c);if(d===p){var m=d-1,x=d+1;f="tozero"===t.rangemode?d<0?[m,0]:[0,x]:"nonnegative"===t.rangemode?[Math.max(0,m),Math.max(0,x)]:[m,x]}else h&&("linear"!==t.type&&"-"!==t.type||("tozero"===t.rangemode?(o.val>=0&&(o={val:0,pad:0}),s.val<=0&&(s={val:0,pad:0})):"nonnegative"===t.rangemode&&(o.val-h*y(o)<0&&(o={val:0,pad:0}),s.val<0&&(s={val:1,pad:0})),h=(s.val-o.val)/(t._length-y(o)-y(s))),f=[o.val-h*y(o),s.val+h*y(s)]);return f[0]===f[1]&&("tozero"===t.rangemode?f=f[0]<0?[f[0],0]:f[0]>0?[0,f[0]]:[0,1]:(f=[f[0]-1,f[0]+1],"nonnegative"===t.rangemode&&(f[0]=Math.max(0,f[0])))),g&&f.reverse(),a.simpleMap(f,t.l2r||Number)}function l(t){var e=t._length/20;return"domain"===t.constrain&&t._inputDomain&&(e*=(t._inputDomain[1]-t._inputDomain[0])/(t.domain[1]-t.domain[0])),function(t){return t.pad+(t.extrapad?e:0)}}function s(t){return n(t)&&Math.abs(t)<i}function c(t,e){return t<=e}function u(t,e){return t>=e}e.exports={getAutoRange:o,makePadFn:l,doAutoRange:function(t){t._length||t.setScale();var e,r=t._min&&t._max&&t._min.length&&t._max.length;t.autorange&&r&&(t.range=o(t),t._r=t.range.slice(),t._rl=a.simpleMap(t._r,t.r2l),(e=t._input).range=t.range.slice(),e.autorange=t.autorange);if(t._anchorAxis&&t._anchorAxis.rangeslider){var n=t._anchorAxis.rangeslider[t._name];n&&"auto"===n.rangemode&&(n.range=r?o(t):t._rangeInitial?t._rangeInitial.slice():t.range.slice()),(e=t._anchorAxis._input).rangeslider[t._name]=a.extendFlat({},n)}},expand:function(t,e,r){if(!function(t){return t.autorange||t._rangesliderAutorange}(t)||!e)return;t._min||(t._min=[]);t._max||(t._max=[]);r||(r={});t._m||t.setScale();var a,o,l,f,d,p,h,g,y,v,m,x,b=e.length,_=r.padded||!1,w=r.tozero&&("linear"===t.type||"-"===t.type),k="log"===t.type,M=!1;function T(t){if(Array.isArray(t))return M=!0,function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}var A=T((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),L=T((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),C=T(r.vpadplus||r.vpad),S=T(r.vpadminus||r.vpad);if(!M){if(m=1/0,x=-1/0,k)for(a=0;a<b;a++)(f=e[a])<m&&f>0&&(m=f),f>x&&f<i&&(x=f);else for(a=0;a<b;a++)(f=e[a])<m&&f>-i&&(m=f),f>x&&f<i&&(x=f);e=[m,x],b=2}function O(r){if(d=e[r],n(d))for(g=A(r),y=L(r),m=d-S(r),x=d+C(r),k&&m<x/10&&(m=x/10),p=t.c2l(m),h=t.c2l(x),w&&(p=Math.min(0,p),h=Math.max(0,h)),l=0;l<2;l++){var a=l?h:p;if(s(a)){var i=l?t._max:t._min,b=l?g:y,M=l?u:c;for(v=!0,o=0;o<i.length&&v;o++){if(f=i[o],M(f.val,a)&&f.pad>=b&&(f.extrapad||!_)){v=!1;break}M(a,f.val)&&f.pad<=b&&(_||!f.extrapad)&&(i.splice(o,1),o--)}if(v){var T=w&&0===a;i.push({val:a,pad:T?0:b,extrapad:!T&&_})}}}}var P=Math.min(6,b);for(a=0;a<P;a++)O(a);for(a=b-1;a>=P;a--)O(a)}}},{"../../constants/numerical":145,"../../lib":163,"fast-isnumeric":13}],207:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../../plots/plots"),o=t("../../registry"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("../../components/titles"),u=t("../../components/color"),f=t("../../components/drawing"),d=t("../../constants/numerical"),p=d.ONEAVGYEAR,h=d.ONEAVGMONTH,g=d.ONEDAY,y=d.ONEHOUR,v=d.ONEMIN,m=d.ONESEC,x=d.MINUS_SIGN,b=d.BADNUM,_=t("../../constants/alignment").MID_SHIFT,w=t("../../constants/alignment").LINE_SPACING,k=e.exports={};k.setConvert=t("./set_convert");var M=t("./axis_autotype"),T=t("./axis_ids");k.id2name=T.id2name,k.name2id=T.name2id,k.cleanId=T.cleanId,k.list=T.list,k.listIds=T.listIds,k.getFromId=T.getFromId,k.getFromTrace=T.getFromTrace;var A=t("./autorange");k.expand=A.expand,k.getAutoRange=A.getAutoRange,k.coerceRef=function(t,e,r,n,a,i){var o=n.charAt(n.length-1),s=r._fullLayout._subplots[o+"axis"],c=n+"ref",u={};return a||(a=s[0]||i),i||(i=a),u[c]={valType:"enumerated",values:s.concat(i?[i]:[]),dflt:a},l.coerce(t,e,u,c)},k.coercePosition=function(t,e,r,n,a,i){var o,s;if("paper"===n||"pixel"===n)o=l.ensureNumber,s=r(a,i);else{var c=k.getFromId(e,n);s=r(a,i=c.fraction2r(i)),o=c.cleanPos}t[a]=o(s)},k.cleanPosition=function(t,e,r){return("paper"===r||"pixel"===r?l.ensureNumber:k.getFromId(e,r).cleanPos)(t)};var L=k.getDataConversions=function(t,e,r,n){var a,i="x"===r||"y"===r||"z"===r?r:n;if(Array.isArray(i)){if(a={type:M(n),_categories:[]},k.setConvert(a),"category"===a.type)for(var o=0;o<n.length;o++)a.d2c(n[o])}else a=k.getFromTrace(t,e,i);return a?{d2c:a.d2c,c2d:a.c2d}:"ids"===i?{d2c:S,c2d:S}:{d2c:C,c2d:C}};function C(t){return+t}function S(t){return String(t)}k.getDataToCoordFunc=function(t,e,r,n){return L(t,e,r,n).d2c},k.counterLetter=function(t){var e=t.charAt(0);return"x"===e?"y":"y"===e?"x":void 0},k.minDtick=function(t,e,r,n){-1===["log","category"].indexOf(t.type)&&n?void 0===t._minDtick?(t._minDtick=e,t._forceTick0=r):t._minDtick&&((t._minDtick/e+1e-6)%1<2e-6&&((r-t._forceTick0)/e%1+1.000001)%1<2e-6?(t._minDtick=e,t._forceTick0=r):((e/t._minDtick+1e-6)%1>2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},k.saveRangeInitial=function(t,e){for(var r=k.list(t,"",!0),n=!1,a=0;a<r.length;a++){var i=r[a],o=void 0===i._rangeInitial,l=o||!(i.range[0]===i._rangeInitial[0]&&i.range[1]===i._rangeInitial[1]);(o&&!1===i.autorange||e&&l)&&(i._rangeInitial=i.range.slice(),n=!0)}return n},k.saveShowSpikeInitial=function(t,e){for(var r=k.list(t,"",!0),n=!1,a="on",i=0;i<r.length;i++){var o=r[i],l=void 0===o._showSpikeInitial,s=l||!(o.showspikes===o._showspikes);(l||e&&s)&&(o._showSpikeInitial=o.showspikes,n=!0),"on"!==a||o.showspikes||(a="off")}return t._fullLayout._cartesianSpikesEnabled=a,n},k.autoBin=function(t,e,r,n,i){var o,s,c=l.aggNums(Math.min,null,t),u=l.aggNums(Math.max,null,t);if(i||(i=e.calendar),"category"===e.type)return{start:c-.5,end:u+.5,size:1,_dataSpan:u-c};if(r)o=(u-c)/r;else{var f=l.distinctVals(t),d=Math.pow(10,Math.floor(Math.log(f.minDiff)/Math.LN10)),p=d*l.roundUp(f.minDiff/d,[.9,1.9,4.9,9.9],!0);o=Math.max(p,2*l.stdev(t)/Math.pow(t.length,n?.25:.4)),a(o)||(o=1)}s="log"===e.type?{type:"linear",range:[c,u]}:{type:e.type,range:l.simpleMap([c,u],e.c2r,0,i),calendar:i},k.setConvert(s),k.autoTicks(s,o);var h,y=k.tickIncrement(k.tickFirst(s),s.dtick,"reverse",i);if("number"==typeof s.dtick)h=(y=function(t,e,r,n,i){var o=0,l=0,s=0,c=0;function u(e){return(1+100*(e-t)/r.dtick)%100<2}for(var f=0;f<e.length;f++)e[f]%1==0?s++:a(e[f])||c++,u(e[f])&&o++,u(e[f]+r.dtick/2)&&l++;var d=e.length-c;if(s===d&&"date"!==r.type)r.dtick<1?t=n-.5*r.dtick:(t-=.5)+r.dtick<n&&(t+=r.dtick);else if(l<.1*d&&(o>.3*d||u(n)||u(i))){var p=r.dtick/2;t+=t+p<n?p:-p}return t}(y,t,s,c,u))+(1+Math.floor((u-y)/s.dtick))*s.dtick;else for("M"===s.dtick.charAt(0)&&(y=function(t,e,r,n,a){var i=l.findExactDates(e,a);if(i.exactDays>.8){var o=Number(r.substr(1));i.exactYears>.8&&o%12==0?t=k.tickIncrement(t,"M6","reverse")+1.5*g:i.exactMonths>.8?t=k.tickIncrement(t,"M1","reverse")+15.5*g:t-=g/2;var s=k.tickIncrement(t,r);if(s<=n)return s}return t}(y,t,s.dtick,c,i)),h=y,0;h<=u;)h=k.tickIncrement(h,s.dtick,!1,i),0;return{start:e.c2r(y,0,i),end:e.c2r(h,0,i),size:s.dtick,_dataSpan:u-c}},k.prepTicks=function(t){var e=l.simpleMap(t.range,t.r2l);if("auto"===t.tickmode||!t.dtick){var r,n=t.nticks;n||("category"===t.type?(r=t.tickfont?1.2*(t.tickfont.size||12):15,n=t._length/r):(r="y"===t._id.charAt(0)?40:80,n=l.constrain(t._length/r,4,9)+1),"radialaxis"===t._name&&(n*=2)),"array"===t.tickmode&&(n*=100),k.autoTicks(t,Math.abs(e[1]-e[0])/n),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t.l2r(t._forceTick0))}t.tick0||(t.tick0="date"===t.type?"2000-01-01":0),F(t)},k.calcTicks=function(t){k.prepTicks(t);var e=l.simpleMap(t.range,t.r2l);if("array"===t.tickmode)return function(t){var e,r,n=t.tickvals,a=t.ticktext,i=new Array(n.length),o=l.simpleMap(t.range,t.r2l),s=1.0001*o[0]-1e-4*o[1],c=1.0001*o[1]-1e-4*o[0],u=Math.min(s,c),f=Math.max(s,c),d=0;Array.isArray(a)||(a=[]);var p="category"===t.type?t.d2l_noadd:t.d2l;"log"===t.type&&"L"!==String(t.dtick).charAt(0)&&(t.dtick="L"+Math.pow(10,Math.floor(Math.min(t.range[0],t.range[1]))-1));for(r=0;r<n.length;r++)(e=p(n[r]))>u&&e<f&&(void 0===a[r]?i[d]=k.tickText(t,e):i[d]=j(t,e,String(a[r])),d++);d<n.length&&i.splice(d,n.length-d);return i}(t);t._tmin=k.tickFirst(t);var r=1.0001*e[0]-1e-4*e[1],n=1.0001*e[1]-1e-4*e[0],a=e[1]<e[0];if(t._tmin<r!==a)return[];var i=[];"category"===t.type&&(n=a?Math.max(-.5,n):Math.min(t._categories.length-.5,n));for(var o=null,s=Math.max(1e3,t._length||0),c=t._tmin;(a?c>=n:c<=n)&&!(i.length>s||c===o);c=k.tickIncrement(c,t.dtick,a,t.calendar))o=c,i.push(c);"angular"===t._id&&360===Math.abs(e[1]-e[0])&&i.pop(),t._tmax=i[i.length-1],t._prevDateHead="",t._inCalcTicks=!0;for(var u=new Array(i.length),f=0;f<i.length;f++)u[f]=k.tickText(t,i[f]);return t._inCalcTicks=!1,u};var O=[2,5,10],P=[1,2,3,6,12],D=[1,2,5,10,15,30],z=[1,2,3,7,14],E=[-.046,0,.301,.477,.602,.699,.778,.845,.903,.954,1],I=[-.301,0,.301,.699,1],N=[15,30,45,90,180];function R(t,e,r){return e*l.roundUp(t/e,r)}function F(t){var e=t.dtick;if(t._tickexponent=0,a(e)||"string"==typeof e||(e=1),"category"===t.type&&(t._tickround=null),"date"===t.type){var r=t.r2l(t.tick0),n=t.l2r(r).replace(/(^-|i)/g,""),i=n.length;if("M"===String(e).charAt(0))i>10||"01-01"!==n.substr(5)?t._tickround="d":t._tickround=+e.substr(1)%12==0?"y":"m";else if(e>=g&&i<=10||e>=15*g)t._tickround="d";else if(e>=v&&i<=16||e>=y)t._tickround="M";else if(e>=m&&i<=19||e>=v)t._tickround="S";else{var o=t.l2r(r+e).replace(/^-/,"").length;t._tickround=Math.max(i,o)-20}}else if(a(e)||"L"===e.charAt(0)){var l=t.range.map(t.r2d||Number);a(e)||(e=Number(e.substr(1))),t._tickround=2-Math.floor(Math.log(e)/Math.LN10+.01);var s=Math.max(Math.abs(l[0]),Math.abs(l[1])),c=Math.floor(Math.log(s)/Math.LN10+.01);Math.abs(c)>3&&(H(t.exponentformat)&&!q(c)?t._tickexponent=3*Math.round((c-1)/3):t._tickexponent=c)}else t._tickround=null}function j(t,e,r){var n=t.tickfont||{};return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}k.autoTicks=function(t,e){var r;function n(t){return Math.pow(t,Math.floor(Math.log(e)/Math.LN10))}if("date"===t.type){t.tick0=l.dateTick0(t.calendar);var i=2*e;i>p?(e/=p,r=n(10),t.dtick="M"+12*R(e,r,O)):i>h?(e/=h,t.dtick="M"+R(e,1,P)):i>g?(t.dtick=R(e,g,z),t.tick0=l.dateTick0(t.calendar,!0)):i>y?t.dtick=R(e,y,P):i>v?t.dtick=R(e,v,D):i>m?t.dtick=R(e,m,D):(r=n(10),t.dtick=R(e,r,O))}else if("log"===t.type){t.tick0=0;var o=l.simpleMap(t.range,t.r2l);if(e>.7)t.dtick=Math.ceil(e);else if(Math.abs(o[1]-o[0])<1){var s=1.5*Math.abs((o[1]-o[0])/e);e=Math.abs(Math.pow(10,o[1])-Math.pow(10,o[0]))/s,r=n(10),t.dtick="L"+R(e,r,O)}else t.dtick=e>.3?"D2":"D1"}else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):"angular"===t._id?(t.tick0=0,r=1,t.dtick=R(e,r,N)):(t.tick0=0,r=n(10),t.dtick=R(e,r,O));if(0===t.dtick&&(t.dtick=1),!a(t.dtick)&&"string"!=typeof t.dtick){var c=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(c)}},k.tickIncrement=function(t,e,r,i){var o=r?-1:1;if(a(e))return t+o*e;var s=e.charAt(0),c=o*Number(e.substr(1));if("M"===s)return l.incrementMonth(t,c,i);if("L"===s)return Math.log(Math.pow(10,t)+c)/Math.LN10;if("D"===s){var u="D2"===e?I:E,f=t+.01*o,d=l.roundUp(l.mod(f,1),u,r);return Math.floor(f)+Math.log(n.round(Math.pow(10,d),1))/Math.LN10}throw"unrecognized dtick "+String(e)},k.tickFirst=function(t){var e=t.r2l||Number,r=l.simpleMap(t.range,e),i=r[1]<r[0],o=i?Math.floor:Math.ceil,s=1.0001*r[0]-1e-4*r[1],c=t.dtick,u=e(t.tick0);if(a(c)){var f=o((s-u)/c)*c+u;return"category"===t.type&&(f=l.constrain(f,0,t._categories.length-1)),f}var d=c.charAt(0),p=Number(c.substr(1));if("M"===d){for(var h,g,y,v=0,m=u;v<10;){if(((h=k.tickIncrement(m,c,i,t.calendar))-s)*(m-s)<=0)return i?Math.min(m,h):Math.max(m,h);g=(s-(m+h)/2)/(h-m),y=d+(Math.abs(Math.round(g))||1)*p,m=k.tickIncrement(m,y,g<0?!i:i,t.calendar),v++}return l.error("tickFirst did not converge",t),m}if("L"===d)return Math.log(o((Math.pow(10,s)-u)/p)*p+u)/Math.LN10;if("D"===d){var x="D2"===c?I:E,b=l.roundUp(l.mod(s,1),x,i);return Math.floor(s)+Math.log(n.round(Math.pow(10,b),1))/Math.LN10}throw"unrecognized dtick "+String(c)},k.tickText=function(t,e,r){var n,i,o=j(t,e),s="array"===t.tickmode,c=r||s,u="category"===t.type?t.d2l_noadd:t.d2l;if(s&&Array.isArray(t.ticktext)){var f=l.simpleMap(t.range,t.r2l),d=Math.abs(f[1]-f[0])/1e4;for(i=0;i<t.ticktext.length&&!(Math.abs(e-u(t.tickvals[i]))<d);i++);if(i<t.ticktext.length)return o.text=String(t.ticktext[i]),o}function p(n){var a;return void 0===n||(r?"none"===n:(a={first:t._tmin,last:t._tmax}[n],"all"!==n&&e!==a))}return n=r?"never":"none"!==t.exponentformat&&p(t.showexponent)?"hide":"","date"===t.type?function(t,e,r,n){var i=t._tickround,o=r&&t.hoverformat||k.getTickFormat(t);n&&(i=a(i)?4:{y:"m",m:"d",d:"M",M:"S",S:4}[i]);var s,c=l.formatDate(e.x,o,i,t._dateFormat,t.calendar,t._extraFormat),u=c.indexOf("\n");-1!==u&&(s=c.substr(u+1),c=c.substr(0,u));n&&("00:00:00"===c||"00:00"===c?(c=s,s=""):8===c.length&&(c=c.replace(/:00$/,"")));s&&(r?"d"===i?c+=", "+s:c=s+(c?", "+c:""):t._inCalcTicks&&s===t._prevDateHead||(c+="<br>"+s,t._prevDateHead=s));e.text=c}(t,o,r,c):"log"===t.type?function(t,e,r,n,i){var o=t.dtick,s=e.x,c=t.tickformat;"never"===i&&(i="");!n||"string"==typeof o&&"L"===o.charAt(0)||(o="L3");if(c||"string"==typeof o&&"L"===o.charAt(0))e.text=V(Math.pow(10,s),t,i,n);else if(a(o)||"D"===o.charAt(0)&&l.mod(s+.01,1)<.1){var u=Math.round(s);-1!==["e","E","power"].indexOf(t.exponentformat)||H(t.exponentformat)&&q(u)?(e.text=0===u?1:1===u?"10":u>1?"10<sup>"+u+"</sup>":"10<sup>"+x+-u+"</sup>",e.fontSize*=1.25):(e.text=V(Math.pow(10,s),t,"","fakehover"),"D1"===o&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6))}else{if("D"!==o.charAt(0))throw"unrecognized dtick "+String(o);e.text=String(Math.round(Math.pow(10,l.mod(s,1)))),e.fontSize*=.75}if("D1"===t.dtick){var f=String(e.text).charAt(0);"0"!==f&&"1"!==f||("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(s<0?.5:.25)))}}(t,o,0,c,n):"category"===t.type?function(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r="");e.text=String(r)}(t,o):"angular"===t._id?function(t,e,r,n,a){if("radians"!==t.thetaunit||r)e.text=V(e.x,t,a,n);else{var i=e.x/180;if(0===i)e.text="0";else{var o=function(t){function e(t,e){return Math.abs(t-e)<=1e-6}var r=function(t){var r=1;for(;!e(Math.round(t*r)/r,t);)r*=10;return r}(t),n=t*r,a=Math.abs(function t(r,n){return e(n,0)?r:t(n,r%n)}(n,r));return[Math.round(n/a),Math.round(r/a)]}(i);if(o[1]>=100)e.text=V(l.deg2rad(e.x),t,a,n);else{var s=e.x<0;1===o[1]?1===o[0]?e.text="\u03c0":e.text=o[0]+"\u03c0":e.text=["<sup>",o[0],"</sup>","\u2044","<sub>",o[1],"</sub>","\u03c0"].join(""),s&&(e.text=x+e.text)}}}}(t,o,r,c,n):function(t,e,r,n,a){"never"===a?a="":"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(a="hide");e.text=V(e.x,t,a,n)}(t,o,0,c,n),t.tickprefix&&!p(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!p(t.showticksuffix)&&(o.text+=t.ticksuffix),o},k.hoverLabelText=function(t,e,r){if(r!==b&&r!==e)return k.hoverLabelText(t,e)+" - "+k.hoverLabelText(t,r);var n="log"===t.type&&e<=0,a=k.tickText(t,t.c2l(n?-e:e),"hover").text;return n?0===e?"0":x+a:a};var B=["f","p","n","\u03bc","m","","k","M","G","T"];function H(t){return"SI"===t||"B"===t}function q(t){return t>14||t<-15}function V(t,e,r,n){var i=t<0,o=e._tickround,s=r||e.exponentformat||"B",c=e._tickexponent,u=k.getTickFormat(e),f=e.separatethousands;if(n){var d={exponentformat:s,dtick:"none"===e.showexponent?e.dtick:a(t)&&Math.abs(t)||1,range:"none"===e.showexponent?e.range.map(e.r2d):[0,t||1]};F(d),o=(Number(d._tickround)||0)+4,c=d._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return e._numFormat(u)(t).replace(/-/g,x);var p,h=Math.pow(10,-o)/2;if("none"===s&&(c=0),(t=Math.abs(t))<h)t="0",i=!1;else{if(t+=h,c&&(t*=Math.pow(10,-c),o+=c),0===o)t=String(Math.floor(t));else if(o<0){t=(t=String(Math.round(t))).substr(0,t.length+o);for(var g=o;g<0;g++)t+="0"}else{var y=(t=String(t)).indexOf(".")+1;y&&(t=t.substr(0,y+o).replace(/\.?0+$/,""))}t=l.numSeparate(t,e._separators,f)}c&&"hide"!==s&&(H(s)&&q(c)&&(s="power"),p=c<0?x+-c:"power"!==s?"+"+c:String(c),"e"===s?t+="e"+p:"E"===s?t+="E"+p:"power"===s?t+="\xd710<sup>"+p+"</sup>":"B"===s&&9===c?t+="B":H(s)&&(t+=B[c/3+5]));return i?x+t:t}function U(t,e){for(var r=0;r<e.length;r++)-1===t.indexOf(e[r])&&t.push(e[r])}function G(t,e,r){var n,a,i=[],o=[],s=t.layout;for(n=0;n<e.length;n++)i.push(k.getFromId(t,e[n]));for(n=0;n<r.length;n++)o.push(k.getFromId(t,r[n]));var c=Object.keys(i[0]),u=["anchor","domain","overlaying","position","side","tickangle"],f=["linear","log"];for(n=0;n<c.length;n++){var d=c[n],p=i[0][d],h=o[0][d],g=!0,y=!1,v=!1;if("_"!==d.charAt(0)&&"function"!=typeof p&&-1===u.indexOf(d)){for(a=1;a<i.length&&g;a++){var m=i[a][d];"type"===d&&-1!==f.indexOf(p)&&-1!==f.indexOf(m)&&p!==m?y=!0:m!==p&&(g=!1)}for(a=1;a<o.length&&g;a++){var x=o[a][d];"type"===d&&-1!==f.indexOf(h)&&-1!==f.indexOf(x)&&h!==x?v=!0:o[a][d]!==h&&(g=!1)}g&&(y&&(s[i[0]._name].type="linear"),v&&(s[o[0]._name].type="linear"),Y(s,d,i,o,t._fullLayout._dfltTitle))}}for(n=0;n<t._fullLayout.annotations.length;n++){var b=t._fullLayout.annotations[n];-1!==e.indexOf(b.xref)&&-1!==r.indexOf(b.yref)&&l.swapAttrs(s.annotations[n],["?"])}}function Y(t,e,r,n,a){var i,o=l.nestedProperty,s=o(t[r[0]._name],e).get(),c=o(t[n[0]._name],e).get();for("title"===e&&(s===a.x&&(s=a.y),c===a.y&&(c=a.x)),i=0;i<r.length;i++)o(t,r[i]._name+"."+e).set(c);for(i=0;i<n.length;i++)o(t,n[i]._name+"."+e).set(s)}k.getTickFormat=function(t){var e,r,n,a,i,o,l,s;function c(t){return"string"!=typeof t?t:Number(t.replace("M",""))*h}function u(t,e){var r=["L","D"];if(typeof t==typeof e){if("number"==typeof t)return t-e;var n=r.indexOf(t.charAt(0)),a=r.indexOf(e.charAt(0));return n===a?Number(t.replace(/(L|D)/g,""))-Number(e.replace(/(L|D)/g,"")):n-a}return"number"==typeof t?1:-1}function f(t,e){var r=null===e[0],n=null===e[1],a=u(t,e[0])>=0,i=u(t,e[1])<=0;return(r||a)&&(n||i)}if(t.tickformatstops&&t.tickformatstops.length>0)switch(t.type){case"date":case"linear":for(e=0;e<t.tickformatstops.length;e++)if((n=t.tickformatstops[e]).enabled&&(a=t.dtick,i=n.dtickrange,o=void 0,void 0,void 0,o=c||function(t){return t},l=i[0],s=i[1],(!l&&"number"!=typeof l||o(l)<=o(a))&&(!s&&"number"!=typeof s||o(s)>=o(a)))){r=n;break}break;case"log":for(e=0;e<t.tickformatstops.length;e++)if((n=t.tickformatstops[e]).enabled&&f(t.dtick,n.dtickrange)){r=n;break}}return r?r.value:t.tickformat},k.getSubplots=function(t,e){var r=t._fullLayout._subplots,n=r.cartesian.concat(r.gl2d||[]),a=e?k.findSubplotsWithAxis(n,e):n;return a.sort(function(t,e){var r=t.substr(1).split("y"),n=e.substr(1).split("y");return r[0]===n[0]?+r[1]-+n[1]:+r[0]-+n[0]}),a},k.findSubplotsWithAxis=function(t,e){for(var r=new RegExp("x"===e._id.charAt(0)?"^"+e._id+"y":e._id+"$"),n=[],a=0;a<t.length;a++){var i=t[a];r.test(i)&&n.push(i)}return n},k.makeClipPaths=function(t){var e=t._fullLayout;if(!e._hasOnlyLargeSploms){var r,a,i={_offset:0,_length:e.width,_id:""},o={_offset:0,_length:e.height,_id:""},l=k.list(t,"x",!0),s=k.list(t,"y",!0),c=[];for(r=0;r<l.length;r++)for(c.push({x:l[r],y:o}),a=0;a<s.length;a++)0===r&&c.push({x:i,y:s[a]}),c.push({x:l[r],y:s[a]});var u=e._clips.selectAll(".axesclip").data(c,function(t){return t.x._id+t.y._id});u.enter().append("clipPath").classed("axesclip",!0).attr("id",function(t){return"clip"+e._uid+t.x._id+t.y._id}).append("rect"),u.exit().remove(),u.each(function(t){n.select(this).select("rect").attr({x:t.x._offset||0,y:t.y._offset||0,width:t.x._length||1,height:t.y._length||1})})}},k.doTicks=function(t,e,r){var n=t._fullLayout;"redraw"===e&&n._paper.selectAll("g.subplot").each(function(t){var e=n._plots[t],r=e.xaxis,a=e.yaxis;e.xaxislayer.selectAll("."+r._id+"tick").remove(),e.yaxislayer.selectAll("."+a._id+"tick").remove(),e.gridlayer&&e.gridlayer.selectAll("path").remove(),e.zerolinelayer&&e.zerolinelayer.selectAll("path").remove(),n._infolayer.select(".g-"+r._id+"title").remove(),n._infolayer.select(".g-"+a._id+"title").remove()});var a=e&&"redraw"!==e?e:k.listIds(t);l.syncOrAsync(a.map(function(e){return function(){if(e){var n=k.doTicksSingle(t,e,r),a=k.getFromId(t,e);return a._r=a.range.slice(),a._rl=l.simpleMap(a._r,a.r2l),n}}}))},k.doTicksSingle=function(t,e,r){var d,p=t._fullLayout,h=!1;l.isPlainObject(e)?(d=e,h=!0):d=k.getFromId(t,e),d.setScale();var g,y,v,m,x,b,M=d._id,A=M.charAt(0),L=k.counterLetter(M),C=d._vals=k.calcTicks(d),S=function(t){return[t.text,t.x,d.mirror,t.font,t.fontSize,t.fontColor].join("_")},O=M+"tick",P=M+"grid",D=M+"zl",z=(d.linewidth||1)/2,E="outside"===d.ticks?d.ticklen:0,I=0,N=f.crispRound(t,d.gridwidth,1),R=f.crispRound(t,d.zerolinewidth,N),F=f.crispRound(t,d.tickwidth,1);if(d._counterangle&&"outside"===d.ticks){var j=d._counterangle*Math.PI/180;E=d.ticklen*Math.cos(j)+1,I=d.ticklen*Math.sin(j)}if(d.showticklabels&&("outside"===d.ticks||d.showline)&&(E+=.2*d.tickfont.size),"x"===A)g=["bottom","top"],y=d._transfn||function(t){return"translate("+(d._offset+d.l2p(t.x))+",0)"},v=function(t,e){if(d._counterangle){var r=d._counterangle*Math.PI/180;return"M0,"+t+"l"+Math.sin(r)*e+","+Math.cos(r)*e}return"M0,"+t+"v"+e};else if("y"===A)g=["left","right"],y=d._transfn||function(t){return"translate(0,"+(d._offset+d.l2p(t.x))+")"},v=function(t,e){if(d._counterangle){var r=d._counterangle*Math.PI/180;return"M"+t+",0l"+Math.cos(r)*e+","+-Math.sin(r)*e}return"M"+t+",0h"+e};else{if("angular"!==M)return void l.warn("Unrecognized doTicks axis:",M);g=["left","right"],y=d._transfn,v=function(t,e){return"M"+t+",0h"+e}}var B=d.side||g[0],H=[-1,1,B===g[1]?1:-1];if("inside"!==d.ticks==("x"===A)&&(H=H.map(function(t){return-t})),d.visible){d._tickFilter&&(C=C.filter(d._tickFilter));var q=C.filter(W);if("angular"===d._id&&(q=C),h){if(Q(d._axislayer,v(d._pos+z*H[2],H[2]*d.ticklen)),d._counteraxis)tt({gridlayer:d._gridlayer,zerolinelayer:d._zerolinelayer},d._counteraxis);return J(d._axislayer,d._pos)}if(p._has("cartesian")){m=k.getSubplots(t,d);var V={};m.map(function(t){var e=p._plots[t],r=e[L+"axis"],n=r._mainAxis._id;V[n]||(V[n]=1,tt(e,r,t))});var U=d._mainSubplot,G=p._plots[U],Y=[];if(d.ticks){var X=H[2],Z=v(d._mainLinePosition+z*X,X*d.ticklen);d._anchorAxis&&d.mirror&&!0!==d.mirror&&(Z+=v(d._mainMirrorPosition-z*X,-X*d.ticklen)),Q(G[A+"axislayer"],Z),Y=Object.keys(d._linepositions||{})}return Y.map(function(t){var e=p._plots[t][A+"axislayer"],r=d._linepositions[t]||[];function n(t){var e=H[t];return v(r[t]+z*e,e*d.ticklen)}Q(e,n(0)+n(1))}),J(G[A+"axislayer"],d._mainLinePosition)}}function W(t){var e=d.l2p(t.x);return e>1&&e<d._length-1}function Q(t,e){var r=t.selectAll("path."+O).data("inside"===d.ticks?q:C,S);e&&d.ticks?(r.enter().append("path").classed(O,1).classed("ticks",1).classed("crisp",1).call(u.stroke,d.tickcolor).style("stroke-width",F+"px").attr("d",e),r.attr("transform",y),r.exit().remove()):r.remove()}function J(e,r){if(x=e.selectAll("g."+O).data(C,S),!a(r))return x.remove(),void $();if(!d.showticklabels)return x.remove(),$(),void P();var o,c,u,h,g;"x"===A?(o=function(t){return t.dx+I*g},h=r+(E+z)*(g="bottom"===B?1:-1),c=function(t){return t.dy+h+t.fontSize*("bottom"===B?1:-.2)},u=function(t){return a(t)&&0!==t&&180!==t?t*g<0?"end":"start":"middle"}):"y"===A?(g="right"===B?1:-1,c=function(t){return t.dy+t.fontSize*_-I*g},o=function(t){return t.dx+r+(E+z+(90===Math.abs(d.tickangle)?t.fontSize/2:0))*g},u=function(t){return a(t)&&90===Math.abs(t)?"middle":"right"===B?"start":"end"}):"angular"===M&&(d._labelShift=I,d._labelStandoff=E,d._pad=z,o=d._labelx,c=d._labely,u=d._labelanchor);var v=0,k=0,T=[];function L(t,e){t.each(function(t){var r=u(e,t),i=n.select(this),l=i.select(".text-math-group"),d=y.call(i.node(),t)+(a(e)&&0!=+e?" rotate("+e+","+o(t)+","+(c(t)-t.fontSize/2)+")":""),p=function(t,e,r){var n=(t-1)*e;if("x"===A){if(r<-60||60<r)return-.5*n;if("top"===B)return-n}else{if((r*="left"===B?1:-1)<-30)return-n;if(r<30)return-.5*n}return 0}(s.lineCount(i),w*t.fontSize,a(e)?+e:0);if(p&&(d+=" translate(0, "+p+")"),l.empty())i.select("text").attr({transform:d,"text-anchor":r});else{var h=f.bBox(l.node()).width*{end:-.5,start:.5}[r];l.attr("transform",d+(h?"translate("+h+",0)":""))}})}function P(){if(d.showticklabels){var r=t.getBoundingClientRect(),n=e.node().getBoundingClientRect();d._boundingBox={width:n.width,height:n.height,left:n.left-r.left,right:n.right-r.left,top:n.top-r.top,bottom:n.bottom-r.top}}else{var a,i=p._size;"x"===A?(a="free"===d.anchor?i.t+i.h*(1-d.position):i.t+i.h*(1-d._anchorAxis.domain[{bottom:0,top:1}[d.side]]),d._boundingBox={top:a,bottom:a,left:d._offset,right:d._offset+d._length,width:d._length,height:0}):(a="free"===d.anchor?i.l+i.w*d.position:i.l+i.w*d._anchorAxis.domain[{left:0,right:1}[d.side]],d._boundingBox={left:a,right:a,bottom:d._offset+d._length,top:d._offset,height:d._length,width:0})}if(m){var o=d._counterSpan=[1/0,-1/0];for(b=0;b<m.length;b++){var l=p._plots[m[b]]["x"===A?"yaxis":"xaxis"];s(o,[l._offset,l._offset+l._length])}"free"===d.anchor&&s(o,"x"===A?[d._boundingBox.bottom,d._boundingBox.top]:[d._boundingBox.right,d._boundingBox.left])}function s(t,e){t[0]=Math.min(t[0],e[0]),t[1]=Math.max(t[1],e[1])}}x.enter().append("g").classed(O,1).append("text").attr("text-anchor","middle").each(function(e){var r=n.select(this),a=t._promises.length;r.call(s.positionText,o(e),c(e)).call(f.font,e.font,e.fontSize,e.fontColor).text(e.text).call(s.convertToTspans,t),(a=t._promises[a])?T.push(t._promises.pop().then(function(){L(r,d.tickangle)})):L(r,d.tickangle)}),x.exit().remove(),x.each(function(t){v=Math.max(v,t.fontSize)}),"angular"===M&&x.each(function(t){n.select(this).select("text").call(s.positionText,o(t),c(t))}),L(x,d._lastangle||d.tickangle);var D=l.syncOrAsync([function(){return T.length&&Promise.all(T)},function(){if(L(x,d.tickangle),"x"===A&&!a(d.tickangle)&&("log"!==d.type||"D"!==String(d.dtick).charAt(0))){var t=[];for(x.each(function(e){var r=n.select(this),a=r.select(".text-math-group"),i=d.l2p(e.x);a.empty()&&(a=r.select("text"));var o=f.bBox(a.node());t.push({top:0,bottom:10,height:10,left:i-o.width/2,right:i+o.width/2+2,width:o.width+2})}),b=0;b<t.length-1;b++)if(l.bBoxIntersect(t[b],t[b+1])){k=30;break}k&&(Math.abs((C[C.length-1].x-C[0].x)*d._m)/(C.length-1)<2.5*v&&(k=90),L(x,k)),d._lastangle=k}return $(),M+" done"},P,function(){var e=d._name+".automargin";if("x"===A||"y"===A)if(d.automargin){var r=d.side[0],n={x:0,y:0,r:0,l:0,t:0,b:0};"x"===A?(n.y="free"===d.anchor?d.position:d._anchorAxis.domain["t"===r?1:0],n[r]+=d._boundingBox.height):(n.x="free"===d.anchor?d.position:d._anchorAxis.domain["r"===r?1:0],n[r]+=d._boundingBox.width),d.title!==p._dfltTitle[A]&&(n[r]+=d.titlefont.size),i.autoMargin(t,e,n)}else i.autoMargin(t,e)}]);return D&&D.then&&t._promises.push(D),D}function $(){if(!(r||d.rangeslider&&d.rangeslider.visible&&d._boundingBox&&"bottom"===d.side)){var e,n,a,i,o={selection:x,side:d.side},l=M.charAt(0),s=t._fullLayout._size,u=d.titlefont.size;if(x.size()){var h=f.getTranslate(x.node().parentNode);o.offsetLeft=h.x,o.offsetTop=h.y}var g=10+1.5*u+(d.linewidth?d.linewidth-1:0);"x"===l?(n="free"===d.anchor?{_offset:s.t+(1-(d.position||0))*s.h,_length:0}:T.getFromId(t,d.anchor),a=d._offset+d._length/2,i="top"===d.side?-g-u*(d.showticklabels?1:0):n._length+g+u*(d.showticklabels?1.5:.5),i+=n._offset,o.side||(o.side="bottom")):(n="free"===d.anchor?{_offset:s.l+(d.position||0)*s.w,_length:0}:T.getFromId(t,d.anchor),i=d._offset+d._length/2,a="right"===d.side?n._length+g+u*(d.showticklabels?1:.5):-g-u*(d.showticklabels?.5:0),a+=n._offset,e={rotate:"-90",offset:0},o.side||(o.side="left")),c.draw(t,M+"title",{propContainer:d,propName:d._name+".title",placeholder:p._dfltTitle[l],avoid:o,transform:e,attributes:{x:a,y:i,"text-anchor":"middle"}})}}function K(t,e){return!0===t.visible&&t.xaxis+t.yaxis===e&&(!(!o.traceIs(t,"bar")||t.orientation!=={x:"h",y:"v"}[A])||t.fill&&t.fill.charAt(t.fill.length-1)===A)}function tt(e,r,a){if(!p._hasOnlyLargeSploms){var i=e.gridlayer.selectAll("."+M),o=e.zerolinelayer,s=e["hidegrid"+A]?[]:q,c=d._gridpath||("x"===A?"M0,"+r._offset+"v":"M"+r._offset+",0h")+r._length,f=i.selectAll("path."+P).data(!1===d.showgrid?[]:s,S);if(f.enter().append("path").classed(P,1).classed("crisp",1).attr("d",c).each(function(t){d.zeroline&&("linear"===d.type||"-"===d.type)&&Math.abs(t.x)<d.dtick/100&&n.select(this).remove()}),f.attr("transform",y).call(u.stroke,d.gridcolor||"#ddd").style("stroke-width",N+"px"),"function"==typeof c&&f.attr("d",c),f.exit().remove(),o){for(var h=!1,g=0;g<t._fullData.length;g++)if(K(t._fullData[g],a)){h=!0;break}var v=l.simpleMap(d.range,d.r2l),m=v[0]*v[1]<=0&&d.zeroline&&("linear"===d.type||"-"===d.type)&&s.length&&(h||W({x:0})||!d.showline),x=o.selectAll("path."+D).data(m?[{x:0,id:M}]:[]);x.enter().append("path").classed(D,1).classed("zl",1).classed("crisp",1).attr("d",c).each(function(){o.selectAll("path").sort(function(t,e){return T.idSort(t.id,e.id)})}),x.attr("transform",y).call(u.stroke,d.zerolinecolor||u.defaultLine).style("stroke-width",R+"px"),x.exit().remove()}}}},k.allowAutoMargin=function(t){for(var e=k.list(t,"",!0),r=0;r<e.length;r++){var n=e[r];n.automargin&&i.allowAutoMargin(t,n._name+".automargin"),n.rangeslider&&n.rangeslider.visible&&i.allowAutoMargin(t,"rangeslider"+n._id)}},k.swap=function(t,e){for(var r=function(t,e){var r,n,a=[];for(r=0;r<e.length;r++){var i=[],o=t._fullData[e[r]].xaxis,l=t._fullData[e[r]].yaxis;if(o&&l){for(n=0;n<a.length;n++)-1===a[n].x.indexOf(o)&&-1===a[n].y.indexOf(l)||i.push(n);if(i.length){var s,c=a[i[0]];if(i.length>1)for(n=1;n<i.length;n++)s=a[i[n]],U(c.x,s.x),U(c.y,s.y);U(c.x,[o]),U(c.y,[l])}else a.push({x:[o],y:[l]})}}return a}(t,e),n=0;n<r.length;n++)G(t,r[n].x,r[n].y)}},{"../../components/color":45,"../../components/drawing":70,"../../components/titles":136,"../../constants/alignment":143,"../../constants/numerical":145,"../../lib":163,"../../lib/svg_text_utils":184,"../../plots/plots":239,"../../registry":247,"./autorange":206,"./axis_autotype":208,"./axis_ids":210,"./set_convert":225,d3:10,"fast-isnumeric":13}],208:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../../constants/numerical").BADNUM;e.exports=function(t,e){return function(t,e){for(var r,i=0,o=0,l=Math.max(1,(t.length-1)/1e3),s=0;s<t.length;s+=l)r=t[Math.round(s)],a.isDateTime(r,e)&&(i+=1),n(r)&&(o+=1);return i>2*o}(t,e)?"date":function(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,o=0,l=0;l<t.length;l+=r)e=t[Math.round(l)],a.cleanNumber(e)!==i?n++:"string"==typeof e&&""!==e&&"None"!==e&&o++;return o>2*n}(t)?"category":function(t){if(!t)return!1;for(var e=0;e<t.length;e++)if(n(t[e]))return!0;return!1}(t)?"linear":"-"}},{"../../constants/numerical":145,"../../lib":163,"fast-isnumeric":13}],209:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("./layout_attributes"),o=t("./tick_value_defaults"),l=t("./tick_mark_defaults"),s=t("./tick_label_defaults"),c=t("./category_order_defaults"),u=t("./line_grid_defaults"),f=t("./set_convert");e.exports=function(t,e,r,d,p){var h=d.letter,g=e._id,y=d.font||{},v=r("visible",!d.cheateronly),m=e.type;"date"===m&&n.getComponentMethod("calendars","handleDefaults")(t,e,"calendar",d.calendar);f(e,p);var x=r("autorange",!e.isValidRange(t.range));if(e._rangesliderAutorange=!1,x&&r("rangemode"),r("range"),e.cleanRange(),c(t,e,r,d),"category"===m||d.noHover||r("hoverformat"),!v)return e;var b=r("color"),_=b!==i.color.dflt?b:y.color;return r("title",((p._splomAxes||{})[h]||{})[g]||p._dfltTitle[h]),a.coerceFont(r,"titlefont",{family:y.family,size:Math.round(1.2*y.size),color:_}),o(t,e,r,m),s(t,e,r,m,d),l(t,e,r,d),u(t,e,r,{dfltColor:b,bgColor:d.bgColor,showGrid:d.showGrid,attributes:i}),(e.showline||e.ticks)&&r("mirror"),d.automargin&&r("automargin"),e}},{"../../lib":163,"../../registry":247,"./category_order_defaults":211,"./layout_attributes":219,"./line_grid_defaults":221,"./set_convert":225,"./tick_label_defaults":226,"./tick_mark_defaults":227,"./tick_value_defaults":228}],210:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("./constants");r.id2name=function(t){if("string"==typeof t&&t.match(a.AX_ID_PATTERN)){var e=t.substr(1);return"1"===e&&(e=""),t.charAt(0)+"axis"+e}},r.name2id=function(t){if(t.match(a.AX_NAME_PATTERN)){var e=t.substr(5);return"1"===e&&(e=""),t.charAt(0)+e}},r.cleanId=function(t,e){if(t.match(a.AX_ID_PATTERN)&&(!e||t.charAt(0)===e)){var r=t.substr(1).replace(/^0+/,"");return"1"===r&&(r=""),t.charAt(0)+r}},r.list=function(t,e,n){var a=t._fullLayout;if(!a)return[];var i,o=r.listIds(t,e),l=new Array(o.length);for(i=0;i<o.length;i++){var s=o[i];l[i]=a[s.charAt(0)+"axis"+s.substr(1)]}if(!n){var c=a._subplots.gl3d||[];for(i=0;i<c.length;i++){var u=a[c[i]];e?l.push(u[e+"axis"]):l.push(u.xaxis,u.yaxis,u.zaxis)}}return l},r.listIds=function(t,e){var r=t._fullLayout;if(!r)return[];var n=r._subplots;return e?n[e+"axis"]:n.xaxis.concat(n.yaxis)},r.getFromId=function(t,e,n){var a=t._fullLayout;return"x"===n?e=e.replace(/y[0-9]*/,""):"y"===n&&(e=e.replace(/x[0-9]*/,"")),a[r.id2name(e)]},r.getFromTrace=function(t,e,a){var i=t._fullLayout,o=null;if(n.traceIs(e,"gl3d")){var l=e.scene;"scene"===l.substr(0,5)&&(o=i[l][a+"axis"])}else o=r.getFromId(t,e[a+"axis"]||a);return o},r.idSort=function(t,e){var r=t.charAt(0),n=e.charAt(0);return r!==n?r>n?1:-1:+(t.substr(1)||1)-+(e.substr(1)||1)}},{"../../registry":247,"./constants":212}],211:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){if("category"===e.type){var a,i=t.categoryarray,o=Array.isArray(i)&&i.length>0;o&&(a="array");var l,s=r("categoryorder",a);"array"===s&&(l=r("categoryarray")),o||"array"!==s||(s=e.categoryorder="trace"),"trace"===s?e._initialCategories=[]:"array"===s?e._initialCategories=l.slice():(l=function(t,e){var r,n,a,i=e.dataAttr||t._id.charAt(0),o={};if(e.axData)r=e.axData;else for(r=[],n=0;n<e.data.length;n++){var l=e.data[n];l[i+"axis"]===t._id&&r.push(l)}for(n=0;n<r.length;n++){var s=r[n][i];for(a=0;a<s.length;a++){var c=s[a];null!=c&&(o[c]=1)}}return Object.keys(o)}(e,n).sort(),"category ascending"===s?e._initialCategories=l:"category descending"===s&&(e._initialCategories=l.reverse()))}}},{}],212:[function(t,e,r){"use strict";var n=t("../../lib/regex").counter;e.exports={idRegex:{x:n("x"),y:n("y")},attrRegex:n("[xy]axis"),xAxisMatch:n("xaxis"),yAxisMatch:n("yaxis"),AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,SUBPLOT_PATTERN:/^x([0-9]*)y([0-9]*)$/,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,BENDPX:1.5,REDRAWDELAY:50,SELECTDELAY:100,SELECTID:"-select",DFLTRANGEX:[-1,6],DFLTRANGEY:[-1,4],traceLayerClasses:["heatmaplayer","contourcarpetlayer","contourlayer","barlayer","carpetlayer","violinlayer","boxlayer","ohlclayer","scattercarpetlayer","scatterlayer"],layerValue2layerClass:{"above traces":"above","below traces":"below"}}},{"../../lib/regex":178}],213:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./axis_ids").id2name;e.exports=function(t,e,r,i,o){var l=o._axisConstraintGroups,s=e._id,c=s.charAt(0);if(!e.fixedrange&&(r("constrain"),n.coerce(t,e,{constraintoward:{valType:"enumerated",values:"x"===c?["left","center","right"]:["bottom","middle","top"],dflt:"x"===c?"center":"middle"}},"constraintoward"),t.scaleanchor)){var u=function(t,e,r,n){var i,o,l,s,c=n[a(e)].type,u=[];for(o=0;o<r.length;o++)(l=r[o])!==e&&((s=n[a(l)]).type!==c||s.fixedrange||u.push(l));for(i=0;i<t.length;i++)if(t[i][e]){var f=t[i],d=[];for(o=0;o<u.length;o++)l=u[o],f[l]||d.push(l);return{linkableAxes:d,thisGroup:f}}return{linkableAxes:u,thisGroup:null}}(l,s,i,o),f=n.coerce(t,e,{scaleanchor:{valType:"enumerated",values:u.linkableAxes}},"scaleanchor");if(f){var d=r("scaleratio");d||(d=e.scaleratio=1),function(t,e,r,n,a){var i,o,l,s,c;null===e?((e={})[r]=1,c=t.length,t.push(e)):c=t.indexOf(e);var u=Object.keys(e);for(i=0;i<t.length;i++)if(l=t[i],i!==c&&l[n]){var f=l[n];for(o=0;o<u.length;o++)s=u[o],l[s]=f*a*e[s];return void t.splice(c,1)}if(1!==a)for(o=0;o<u.length;o++)e[u[o]]*=a;e[n]=1}(l,u.thisGroup,s,f,d)}else-1!==i.indexOf(t.scaleanchor)&&n.warn("ignored "+e._name+'.scaleanchor: "'+t.scaleanchor+'" to avoid either an infinite loop and possibly inconsistent scaleratios, or because the targetaxis has fixed range.')}}},{"../../lib":163,"./axis_ids":210}],214:[function(t,e,r){"use strict";var n=t("./axis_ids").id2name,a=t("./scale_zoom"),i=t("./autorange").makePadFn,o=t("../../constants/numerical").ALMOST_EQUAL,l=t("../../constants/alignment").FROM_BL;function s(t,e){var r=t._inputDomain,n=l[t.constraintoward],a=r[0]+(r[1]-r[0])*n;t.domain=t._input.domain=[a+(r[0]-a)/e,a+(r[1]-a)/e]}r.enforce=function(t){var e,r,l,c,u,f,d,p=t._fullLayout,h=p._axisConstraintGroups||[];for(e=0;e<h.length;e++){var g=h[e],y=Object.keys(g),v=1/0,m=0,x=1/0,b={},_={},w=!1;for(r=0;r<y.length;r++)_[l=y[r]]=c=p[n(l)],c._inputDomain?c.domain=c._inputDomain.slice():c._inputDomain=c.domain.slice(),c._inputRange||(c._inputRange=c.range.slice()),c.setScale(),b[l]=u=Math.abs(c._m)/g[l],v=Math.min(v,u),"domain"!==c.constrain&&c._constraintShrinkable||(x=Math.min(x,u)),delete c._constraintShrinkable,m=Math.max(m,u),"domain"===c.constrain&&(w=!0);if(!(v>o*m)||w)for(r=0;r<y.length;r++)if(u=b[l=y[r]],f=(c=_[l]).constrain,u!==x||"domain"===f)if(d=u/x,"range"===f)a(c,d);else{var k=c._inputDomain,M=(c.domain[1]-c.domain[0])/(k[1]-k[0]),T=(c.r2l(c.range[1])-c.r2l(c.range[0]))/(c.r2l(c._inputRange[1])-c.r2l(c._inputRange[0]));if((d/=M)*T<1){c.domain=c._input.domain=k.slice(),a(c,d);continue}if(T<1&&(c.range=c._input.range=c._inputRange.slice(),d*=T),c.autorange&&c._min.length&&c._max.length){var A=c.r2l(c.range[0]),L=c.r2l(c.range[1]),C=(A+L)/2,S=C,O=C,P=Math.abs(L-C),D=C-P*d*1.0001,z=C+P*d*1.0001,E=i(c);s(c,d),c.setScale();var I,N,R=Math.abs(c._m);for(N=0;N<c._min.length;N++)(I=c._min[N].val-E(c._min[N])/R)>D&&I<S&&(S=I);for(N=0;N<c._max.length;N++)(I=c._max[N].val+E(c._max[N])/R)<z&&I>O&&(O=I);d/=(O-S)/(2*P),S=c.l2r(S),O=c.l2r(O),c.range=c._input.range=A<L?[S,O]:[O,S]}s(c,d)}}},r.clean=function(t,e){if(e._inputDomain){for(var r=!1,n=e._id,a=t._fullLayout._axisConstraintGroups,i=0;i<a.length;i++)if(a[i][n]){r=!0;break}r&&"domain"===e.constrain||(e._input.domain=e.domain=e._inputDomain,delete e._inputDomain)}}},{"../../constants/alignment":143,"../../constants/numerical":145,"./autorange":206,"./axis_ids":210,"./scale_zoom":223}],215:[function(t,e,r){"use strict";var n=t("d3"),a=t("tinycolor2"),i=t("has-passive-events"),o=t("../../registry"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("../../lib/clear_gl_canvases"),u=t("../../components/color"),f=t("../../components/drawing"),d=t("../../components/fx"),p=t("../../lib/setcursor"),h=t("../../components/dragelement"),g=t("../../constants/alignment").FROM_TL,y=t("../plots"),v=t("./axes").doTicksSingle,m=t("./axis_ids").getFromId,x=t("./select").prepSelect,b=t("./select").clearSelect,_=t("./scale_zoom"),w=t("./constants"),k=w.MINDRAG,M=w.MINZOOM,T=!0;function A(t,e,r,n){var a=l.ensureSingle(t.draglayer,e,r,function(e){e.classed("drag",!0).style({fill:"transparent","stroke-width":0}).attr("data-subplot",t.id)});return a.call(p,n),a.node()}function L(t,e,r,a,i,o,l){var s=A(t,"rect",e,r);return n.select(s).call(f.setRect,a,i,o,l),s}function C(t,e){for(var r=0;r<t.length;r++)if(!t[r].fixedrange)return e;return""}function S(t,e,r,n,a){var i,o,l,s;for(i=0;i<t.length;i++)(o=t[i]).fixedrange||(l=o._rl[0],s=o._rl[1]-l,o.range=[o.l2r(l+s*e),o.l2r(l+s*r)],n[o._name+".range[0]"]=o.range[0],n[o._name+".range[1]"]=o.range[1]);if(a&&a.length){var c=(e+(1-r))/2;S(a,c,1-c,n)}}function O(t,e){for(var r=0;r<t.length;r++){var n=t[r];n.fixedrange||(n.range=[n.l2r(n._rl[0]-e/n._m),n.l2r(n._rl[1]-e/n._m)])}}function P(t){return 1-(t>=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function D(t,e,r,n,a){return t.append("path").attr("class","zoombox").style({fill:e>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("transform","translate("+r+", "+n+")").attr("d",a+"Z")}function z(t,e,r){return t.append("path").attr("class","zoombox-corners").style({fill:u.background,stroke:u.defaultLine,"stroke-width":1,opacity:0}).attr("transform","translate("+e+", "+r+")").attr("d","M0,0Z")}function E(t,e,r,n,a,i){t.attr("d",n+"M"+r.l+","+r.t+"v"+r.h+"h"+r.w+"v-"+r.h+"h-"+r.w+"Z"),I(t,e,a,i)}function I(t,e,r,n){r||(t.transition().style("fill",n>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),e.transition().style("opacity",1).duration(200))}function N(t){n.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function R(t){T&&t.data&&t._context.showTips&&(l.notifier(l._(t,"Double-click to zoom back out"),"long"),T=!1)}function F(t){return"lasso"===t||"select"===t}function j(t){var e=Math.floor(Math.min(t.b-t.t,t.r-t.l,M)/2);return"M"+(t.l-3.5)+","+(t.t-.5+e)+"h3v"+-e+"h"+e+"v-3h-"+(e+3)+"ZM"+(t.r+3.5)+","+(t.t-.5+e)+"h-3v"+-e+"h"+-e+"v-3h"+(e+3)+"ZM"+(t.r+3.5)+","+(t.b+.5-e)+"h-3v"+e+"h"+-e+"v3h"+(e+3)+"ZM"+(t.l-3.5)+","+(t.b+.5-e)+"h3v"+e+"h"+e+"v3h-"+(e+3)+"Z"}function B(t,e){if(i){var r=void 0!==t.onwheel?"wheel":"mousewheel";t._onwheel&&t.removeEventListener(r,t._onwheel),t._onwheel=e,t.addEventListener(r,e,{passive:!1})}else void 0!==t.onwheel?t.onwheel=e:void 0!==t.onmousewheel&&(t.onmousewheel=e)}function H(t){var e=[];for(var r in t)e.push(t[r]);return e}e.exports={makeDragBox:function(t,e,r,i,u,p,T,A){var I,q,V,U,G,Y,X,Z,W,Q,J,$,K,tt,et,rt,nt,at,it,ot,lt,st=t._fullLayout._zoomlayer,ct=T+A==="nsew",ut=1===(T+A).length;function ft(){if(I=e.xaxis,q=e.yaxis,W=I._length,Q=q._length,X=I._offset,Z=q._offset,(V={})[I._id]=I,(U={})[q._id]=q,T&&A)for(var r=e.overlays,n=0;n<r.length;n++){var a=r[n].xaxis;V[a._id]=a;var i=r[n].yaxis;U[i._id]=i}G=H(V),Y=H(U),$=C(G,A),K=C(Y,T),tt=!K&&!$,J=function(t,e,r){for(var n,a,i,o,s=t._fullLayout._axisConstraintGroups,c=!1,u={},f={},d=0;d<s.length;d++){var p=s[d];for(n in e)if(p[n]){for(i in p)("x"===i.charAt(0)?e:r)[i]||(u[i]=1);for(a in r)p[a]&&(c=!0)}for(a in r)if(p[a])for(o in p)("x"===o.charAt(0)?e:r)[o]||(f[o]=1)}c&&(l.extendFlat(u,f),f={});var h={},g=[];for(i in u){var y=m(t,i);g.push(y),h[y._id]=y}var v={},x=[];for(o in f){var b=m(t,o);x.push(b),v[b._id]=b}return{xaHash:h,yaHash:v,xaxes:g,yaxes:x,isSubplotConstrained:c}}(t,V,U),et=J.isSubplotConstrained,rt=A||et,nt=T||et;var o=t._fullLayout;at=o._has("scattergl"),it=o._hasOnlyLargeSploms,ot=it||o._has("splom"),lt=o._has("svg")}ft();var dt=function(t,e,r){return t?"nsew"===t?r?"":"pan"===e?"move":"crosshair":t.toLowerCase()+"-resize":"pointer"}(K+$,t._fullLayout.dragmode,ct),pt=L(e,T+A+"drag",dt,r,i,u,p);if(tt&&!ct)return pt.onmousedown=null,pt.style.pointerEvents="none",pt;var ht,gt,yt,vt,mt,xt,bt,_t,wt,kt,Mt={element:pt,gd:t,plotinfo:e};function Tt(){Mt.plotinfo.selection=!1,b(st)}function At(r,a){if(N(t),2!==r||ut||function(){if(!t._transitioningWithDuration){var e,r,n,a=t._context.doubleClick,i=($?G:[]).concat(K?Y:[]),l={};if("reset+autosize"===a)for(a="autosize",r=0;r<i.length;r++)if((e=i[r])._rangeInitial&&(e.range[0]!==e._rangeInitial[0]||e.range[1]!==e._rangeInitial[1])||!e._rangeInitial&&!e.autorange){a="reset";break}if("autosize"===a)for(r=0;r<i.length;r++)(e=i[r]).fixedrange||(l[e._name+".autorange"]=!0);else if("reset"===a)for(($||et)&&(i=i.concat(J.xaxes)),K&&!et&&(i=i.concat(J.yaxes)),et&&($?K||(i=i.concat(Y)):i=i.concat(G)),r=0;r<i.length;r++)(e=i[r])._rangeInitial?(n=e._rangeInitial,l[e._name+".range[0]"]=n[0],l[e._name+".range[1]"]=n[1]):l[e._name+".autorange"]=!0;t.emit("plotly_doubleclick",null),o.call("relayout",t,l)}}(),ct)d.click(t,a,e.id);else if(1===r&&ut){var i=T?q:I,l="s"===T||"w"===A?0:1,c=i._name+".range["+l+"]",u=function(t,e){var r,a=t.range[e],i=Math.abs(a-t.range[1-e]);return"date"===t.type?a:"log"===t.type?(r=Math.ceil(Math.max(0,-Math.log(i)/Math.LN10))+3,n.format("."+r+"g")(Math.pow(10,a))):(r=Math.floor(Math.log(Math.abs(a))/Math.LN10)-Math.floor(Math.log(i)/Math.LN10)+4,n.format("."+String(r)+"g")(a))}(i,l),f="left",p="middle";if(i.fixedrange)return;T?(p="n"===T?"top":"bottom","right"===i.side&&(f="right")):"e"===A&&(f="right"),t._context.showAxisRangeEntryBoxes&&n.select(pt).call(s.makeEditable,{gd:t,immediate:!0,background:t._fullLayout.paper_bgcolor,text:String(u),fill:i.tickfont?i.tickfont.color:"#444",horizontalAlign:f,verticalAlign:p}).on("edit",function(e){var r=i.d2r(e);void 0!==r&&o.call("relayout",t,c,r)})}}Mt.prepFn=function(e,r,n){var i=t._fullLayout.dragmode;ft(),tt||(ct?e.shiftKey?"pan"===i?i="zoom":F(i)||(i="pan"):e.ctrlKey&&(i="pan"):i="pan"),Mt.minDrag="lasso"===i?1:void 0,F(i)?(Mt.xaxes=G,Mt.yaxes=Y,x(e,r,n,Mt,i)):(Mt.clickFn=At,Tt(),tt||("zoom"===i?(Mt.moveFn=Ct,Mt.doneFn=St,Mt.minDrag=1,function(e,r,n){var i=pt.getBoundingClientRect();ht=r-i.left,gt=n-i.top,yt={l:ht,r:ht,w:0,t:gt,b:gt,h:0},vt=t._hmpixcount?t._hmlumcount/t._hmpixcount:a(t._fullLayout.plot_bgcolor).getLuminance(),xt=!1,bt="xy",kt=!1,_t=D(st,vt,X,Z,mt="M0,0H"+W+"V"+Q+"H0V0"),wt=z(st,X,Z)}(0,r,n)):"pan"===i&&(Mt.moveFn=Nt,Mt.doneFn=Ft)))},h.init(Mt);var Lt={};function Ct(e,r){if(t._transitioningWithDuration)return!1;var n=Math.max(0,Math.min(W,e+ht)),a=Math.max(0,Math.min(Q,r+gt)),i=Math.abs(n-ht),o=Math.abs(a-gt);function l(){bt="",yt.r=yt.l,yt.t=yt.b,wt.attr("d","M0,0Z")}yt.l=Math.min(ht,n),yt.r=Math.max(ht,n),yt.t=Math.min(gt,a),yt.b=Math.max(gt,a),et?i>M||o>M?(bt="xy",i/W>o/Q?(o=i*Q/W,gt>a?yt.t=gt-o:yt.b=gt+o):(i=o*W/Q,ht>n?yt.l=ht-i:yt.r=ht+i),wt.attr("d",j(yt))):l():!K||o<Math.min(Math.max(.6*i,k),M)?i<k||!$?l():(yt.t=0,yt.b=Q,bt="x",wt.attr("d",function(t,e){return"M"+(t.l-.5)+","+(e-M-.5)+"h-3v"+(2*M+1)+"h3ZM"+(t.r+.5)+","+(e-M-.5)+"h3v"+(2*M+1)+"h-3Z"}(yt,gt))):!$||i<Math.min(.6*o,M)?(yt.l=0,yt.r=W,bt="y",wt.attr("d",function(t,e){return"M"+(e-M-.5)+","+(t.t-.5)+"v-3h"+(2*M+1)+"v3ZM"+(e-M-.5)+","+(t.b+.5)+"v3h"+(2*M+1)+"v-3Z"}(yt,ht))):(bt="xy",wt.attr("d",j(yt))),yt.w=yt.r-yt.l,yt.h=yt.b-yt.t,bt&&(kt=!0),t._dragged=kt,E(_t,wt,yt,mt,xt,vt),xt=!0}function St(){if(Math.min(yt.h,yt.w)<2*k)return N(t);"xy"!==bt&&"x"!==bt||S(G,yt.l/W,yt.r/W,Lt,J.xaxes),"xy"!==bt&&"y"!==bt||S(Y,(Q-yt.b)/Q,(Q-yt.t)/Q,Lt,J.yaxes),N(t),Ft(),R(t)}var Ot,Pt,Dt=[0,0,W,Q],zt=null,Et=w.REDRAWDELAY,It=e.mainplot?t._fullLayout._plots[e.mainplot]:e;function Nt(e,r){if(!t._transitioningWithDuration){if("ew"===$||"ns"===K)return $&&O(G,e),K&&O(Y,r),jt([$?-e:0,K?-r:0,W,Q]),void Rt(K,$);if(et&&$&&K){var n="w"===$==("n"===K)?1:-1,a=(e/W+n*r/Q)/2;e=a*W,r=n*a*Q}"w"===$?e=s(G,0,e):"e"===$?e=s(G,1,-e):$||(e=0),"n"===K?r=s(Y,1,r):"s"===K?r=s(Y,0,-r):K||(r=0);var i="w"===$?e:0,o="n"===K?r:0;if(et){var l;if(!$&&1===K.length){for(l=0;l<G.length;l++)G[l].range=G[l]._r.slice(),_(G[l],1-r/Q);i=(e=r*W/Q)/2}if(!K&&1===$.length){for(l=0;l<Y.length;l++)Y[l].range=Y[l]._r.slice(),_(Y[l],1-e/W);o=(r=e*Q/W)/2}}jt([i,o,W-e,Q-r]),Rt(K,$)}function s(t,e,r){for(var n,a,i=1-e,o=0;o<t.length;o++){var l=t[o];if(!l.fixedrange){n=l,a=l._rl[i]+(l._rl[e]-l._rl[i])/P(r/l._length);var s=l.l2r(a);!1!==s&&void 0!==s&&(l.range[e]=s)}}return n._length*(n._rl[e]-a)/(n._rl[e]-n._rl[i])}}function Rt(e,r){var n,a=[];function i(t){for(n=0;n<t.length;n++)t[n].fixedrange||a.push(t[n]._id)}for(rt&&(i(G),i(J.xaxes)),nt&&(i(Y),i(J.yaxes)),Lt={},n=0;n<a.length;n++){var l=a[n];v(t,l,!0);var s=m(t,l);Lt[s._name+".range[0]"]=s.range[0],Lt[s._name+".range[1]"]=s.range[1]}function c(i,o,l){for(n=0;n<i.length;n++){var s=i[n];if((r&&-1!==a.indexOf(s.xref)||e&&-1!==a.indexOf(s.yref))&&(o(t,n),l))return}}c(t._fullLayout.annotations||[],o.getComponentMethod("annotations","drawOne")),c(t._fullLayout.shapes||[],o.getComponentMethod("shapes","drawOne")),c(t._fullLayout.images||[],o.getComponentMethod("images","draw"),!0)}function Ft(){jt([0,0,W,Q]),l.syncOrAsync([y.previousPromises,function(){o.call("relayout",t,Lt)}],t)}function jt(e){var r,n,a,i,s=t._fullLayout,u=s._plots,d=s._subplots.cartesian;if((ot||at)&&c(t),!ot||(o.subplotsRegistry.splom.drag(t),!it)){if(at)for(r=0;r<d.length;r++){a=(n=u[d[r]]).xaxis,i=n.yaxis;var p=n._scene;if(p){var h=l.simpleMap(a.range,a.r2l),g=l.simpleMap(i.range,i.r2l);p.update({range:[h[0],g[0],h[1],g[1]]})}}if(lt){var y=e[2]/I._length,v=e[3]/q._length;for(r=0;r<d.length;r++){a=(n=u[d[r]]).xaxis,i=n.yaxis;var m,x,b,_,w=rt&&!a.fixedrange&&V[a._id],k=nt&&!i.fixedrange&&U[i._id];if(w?(m=y,b=A?e[0]:qt(a,m)):b=Ht(a,m=Bt(a,y,v)),k?(x=v,_=T?e[1]:qt(i,x)):_=Ht(i,x=Bt(i,y,v)),m||x){m||(m=1),x||(x=1);var M=a._offset-b/m,L=i._offset-_/x;n.clipRect.call(f.setTranslate,b,_).call(f.setScale,m,x),n.plot.call(f.setTranslate,M,L).call(f.setScale,1/m,1/x),m===Ot&&x===Pt||(f.setPointGroupScale(n.zoomScalePts,m,x),f.setTextPointsScale(n.zoomScaleTxt,m,x)),f.hideOutsideRangePoints(n.clipOnAxisFalseTraces,n),Ot=m,Pt=x}}}}}function Bt(t,e,r){return t.fixedrange?0:rt&&J.xaHash[t._id]?e:nt&&(et?J.xaHash:J.yaHash)[t._id]?r:0}function Ht(t,e){return e?(t.range=t._r.slice(),_(t,e),qt(t,e)):0}function qt(t,e){return t._length*(1-e)*g[t.constraintoward||"middle"]}return T.length*A.length!=1&&B(pt,function(e){if(t._context.scrollZoom||t._fullLayout._enablescrollzoom){if(Tt(),t._transitioningWithDuration)return e.preventDefault(),void e.stopPropagation();var r=t.querySelector(".plotly");if(ft(),!(r.scrollHeight-r.clientHeight>10||r.scrollWidth-r.clientWidth>10)){clearTimeout(zt);var n=-e.deltaY;if(isFinite(n)||(n=e.wheelDelta/10),isFinite(n)){var a,i=Math.exp(-Math.min(Math.max(n,-20),20)/200),o=It.draglayer.select(".nsewdrag").node().getBoundingClientRect(),s=(e.clientX-o.left)/o.width,c=(o.bottom-e.clientY)/o.height;if(rt){for(A||(s=.5),a=0;a<G.length;a++)u(G[a],s,i);Dt[2]*=i,Dt[0]+=Dt[2]*s*(1/i-1)}if(nt){for(T||(c=.5),a=0;a<Y.length;a++)u(Y[a],c,i);Dt[3]*=i,Dt[1]+=Dt[3]*(1-c)*(1/i-1)}jt(Dt),Rt(T,A),zt=setTimeout(function(){Dt=[0,0,W,Q],Ft()},Et),e.preventDefault()}else l.log("Did not find wheel motion attributes: ",e)}}function u(t,e,r){if(!t.fixedrange){var n=l.simpleMap(t.range,t.r2l),a=n[0]+(n[1]-n[0])*e;t.range=n.map(function(e){return t.l2r(a+(e-a)*r)})}}}),pt},makeDragger:A,makeRectDragger:L,makeZoombox:D,makeCorners:z,updateZoombox:E,xyCorners:j,transitionZoombox:I,removeZoombox:N,showDoubleClickNotifier:R,attachWheelEventHandler:B}},{"../../components/color":45,"../../components/dragelement":67,"../../components/drawing":70,"../../components/fx":87,"../../constants/alignment":143,"../../lib":163,"../../lib/clear_gl_canvases":152,"../../lib/setcursor":182,"../../lib/svg_text_utils":184,"../../registry":247,"../plots":239,"./axes":207,"./axis_ids":210,"./constants":212,"./scale_zoom":223,"./select":224,d3:10,"has-passive-events":16,tinycolor2:28}],216:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/fx"),i=t("../../components/dragelement"),o=t("../../lib/setcursor"),l=t("./dragbox").makeDragBox,s=t("./constants").DRAGGERSIZE;r.initInteractions=function(t){var e=t._fullLayout;if(t._context.staticPlot)n.select(t).selectAll(".drag").remove();else if(e._has("cartesian")||e._has("gl2d")||e._has("splom")){Object.keys(e._plots||{}).sort(function(t,r){if((e._plots[t].mainplot&&!0)===(e._plots[r].mainplot&&!0)){var n=t.split("y"),a=r.split("y");return n[0]===a[0]?Number(n[1]||1)-Number(a[1]||1):Number(n[0]||1)-Number(a[0]||1)}return e._plots[t].mainplot?1:-1}).forEach(function(r){var n=e._plots[r],o=n.xaxis,c=n.yaxis;if(!n.mainplot){var u=l(t,n,o._offset,c._offset,o._length,c._length,"ns","ew");u.onmousemove=function(e){t._fullLayout._rehover=function(){t._fullLayout._hoversubplot===r&&a.hover(t,e,r)},a.hover(t,e,r),t._fullLayout._lasthover=u,t._fullLayout._hoversubplot=r},u.onmouseout=function(e){t._dragging||(t._fullLayout._hoversubplot=null,i.unhover(t,e))},t._context.showAxisDragHandles&&(l(t,n,o._offset-s,c._offset-s,s,s,"n","w"),l(t,n,o._offset+o._length,c._offset-s,s,s,"n","e"),l(t,n,o._offset-s,c._offset+c._length,s,s,"s","w"),l(t,n,o._offset+o._length,c._offset+c._length,s,s,"s","e"))}if(t._context.showAxisDragHandles){if(r===o._mainSubplot){var f=o._mainLinePosition;"top"===o.side&&(f-=s),l(t,n,o._offset+.1*o._length,f,.8*o._length,s,"","ew"),l(t,n,o._offset,f,.1*o._length,s,"","w"),l(t,n,o._offset+.9*o._length,f,.1*o._length,s,"","e")}if(r===c._mainSubplot){var d=c._mainLinePosition;"right"!==c.side&&(d-=s),l(t,n,d,c._offset+.1*c._length,s,.8*c._length,"ns",""),l(t,n,d,c._offset+.9*c._length,s,.1*c._length,"s",""),l(t,n,d,c._offset,s,.1*c._length,"n","")}}});var o=e._hoverlayer.node();o.onmousemove=function(r){r.target=t._fullLayout._lasthover,a.hover(t,r,e._hoversubplot)},o.onclick=function(e){e.target=t._fullLayout._lasthover,a.click(t,e)},o.onmousedown=function(e){t._fullLayout._lasthover.onmousedown(e)},r.updateFx(e)}},r.updateFx=function(t){var e="pan"===t.dragmode?"move":"crosshair";o(t._draggers,e)}},{"../../components/dragelement":67,"../../components/fx":87,"../../lib/setcursor":182,"./constants":212,"./dragbox":215,d3:10}],217:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib");e.exports=function(t){return function(e,r){var i=e[t];if(Array.isArray(i))for(var o=n.subplotsRegistry.cartesian,l=o.idRegex,s=r._subplots,c=s.xaxis,u=s.yaxis,f=s.cartesian,d=r._has("cartesian")||r._has("gl2d"),p=0;p<i.length;p++){var h=i[p];if(a.isPlainObject(h)){var g=h.xref,y=h.yref,v=l.x.test(g),m=l.y.test(y);if(v||m){d||a.pushUnique(r._basePlotModules,o);var x=!1;v&&-1===c.indexOf(g)&&(c.push(g),x=!0),m&&-1===u.indexOf(y)&&(u.push(y),x=!0),x&&v&&m&&f.push(g+y)}}}}}},{"../../lib":163,"../../registry":247}],218:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../lib"),o=t("../plots"),l=t("../../components/drawing"),s=t("../get_data").getModuleCalcData,c=t("./axis_ids"),u=t("./constants"),f=t("../../constants/xmlns_namespaces"),d=i.ensureSingle;function p(t,e,r){return i.ensureSingle(t,e,r,function(t){t.datum(r)})}function h(t,e,r,i,o){for(var c,f,d,p=u.traceLayerClasses,h=t._fullLayout,g=h._modules,y=[],v=[],m=0;m<g.length;m++){var x=(c=g[m]).name,b=a.modules[x].categories;if(b.svg){var _=c.layerName||x+"layer",w=c.plot;d=(f=s(r,w))[0],r=f[1],d.length&&y.push({i:p.indexOf(_),className:_,plotMethod:w,cdModule:d}),b.zoomScale&&v.push("."+_)}}y.sort(function(t,e){return t.i-e.i});var k=e.plot.selectAll("g.mlayer").data(y,function(t){return t.className});if(k.enter().append("g").attr("class",function(t){return t.className}).classed("mlayer",!0),k.exit().remove(),k.order(),k.each(function(r){var a=n.select(this),s=r.className;r.plotMethod(t,e,r.cdModule,a,i,o),"scatterlayer"!==s&&"barlayer"!==s&&l.setClipUrl(a,e.layerClipId)}),h._has("scattergl")&&(c=a.getModule("scattergl"),d=s(r,c)[0],c.plot(t,e,d)),!t._context.staticPlot&&(e._hasClipOnAxisFalse&&(e.clipOnAxisFalseTraces=e.plot.selectAll(".scatterlayer, .barlayer").selectAll(".trace")),v.length)){var M=e.plot.selectAll(v.join(",")).selectAll(".trace");e.zoomScalePts=M.selectAll("path.point"),e.zoomScaleTxt=M.selectAll(".textpoint")}}function g(t,e){var r=e.plotgroup,n=e.id,a=u.layerValue2layerClass[e.xaxis.layer],i=u.layerValue2layerClass[e.yaxis.layer],o=t._fullLayout._hasOnlyLargeSploms;if(e.mainplot){var l=e.mainplotinfo,s=l.plotgroup,f=n+"-x",h=n+"-y";e.gridlayer=l.gridlayer,e.zerolinelayer=l.zerolinelayer,d(l.overlinesBelow,"path",f),d(l.overlinesBelow,"path",h),d(l.overaxesBelow,"g",f),d(l.overaxesBelow,"g",h),e.plot=d(l.overplot,"g",n),d(l.overlinesAbove,"path",f),d(l.overlinesAbove,"path",h),d(l.overaxesAbove,"g",f),d(l.overaxesAbove,"g",h),e.xlines=s.select(".overlines-"+a).select("."+f),e.ylines=s.select(".overlines-"+i).select("."+h),e.xaxislayer=s.select(".overaxes-"+a).select("."+f),e.yaxislayer=s.select(".overaxes-"+i).select("."+h)}else if(o)e.plot=d(r,"g","plot"),e.xlines=d(r,"path","xlines-above"),e.ylines=d(r,"path","ylines-above"),e.xaxislayer=d(r,"g","xaxislayer-above"),e.yaxislayer=d(r,"g","yaxislayer-above");else{var g=d(r,"g","layer-subplot");e.shapelayer=d(g,"g","shapelayer"),e.imagelayer=d(g,"g","imagelayer"),e.gridlayer=d(r,"g","gridlayer"),e.zerolinelayer=d(r,"g","zerolinelayer"),d(r,"path","xlines-below"),d(r,"path","ylines-below"),e.overlinesBelow=d(r,"g","overlines-below"),d(r,"g","xaxislayer-below"),d(r,"g","yaxislayer-below"),e.overaxesBelow=d(r,"g","overaxes-below"),e.plot=d(r,"g","plot"),e.overplot=d(r,"g","overplot"),e.xlines=d(r,"path","xlines-above"),e.ylines=d(r,"path","ylines-above"),e.overlinesAbove=d(r,"g","overlines-above"),d(r,"g","xaxislayer-above"),d(r,"g","yaxislayer-above"),e.overaxesAbove=d(r,"g","overaxes-above"),e.xlines=r.select(".xlines-"+a),e.ylines=r.select(".ylines-"+i),e.xaxislayer=r.select(".xaxislayer-"+a),e.yaxislayer=r.select(".yaxislayer-"+i)}o||(p(e.gridlayer,"g",e.xaxis._id),p(e.gridlayer,"g",e.yaxis._id),e.gridlayer.selectAll("g").sort(c.idSort)),e.xlines.style("fill","none").classed("crisp",!0),e.ylines.style("fill","none").classed("crisp",!0)}function y(t,e){if(t){var r={};for(var a in t.each(function(t){n.select(this).remove(),v(t,e),r[t]=!0}),e._plots)for(var i=e._plots[a].overlays||[],o=0;o<i.length;o++){var l=i[o];r[l.id]&&l.plot.selectAll(".trace").remove()}}}function v(t,e){e._draggers.selectAll("g."+t).remove(),e._defs.select("#clip"+e._uid+t+"plot").remove()}r.name="cartesian",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex=u.idRegex,r.attrRegex=u.attrRegex,r.attributes=t("./attributes"),r.layoutAttributes=t("./layout_attributes"),r.supplyLayoutDefaults=t("./layout_defaults"),r.transitionAxes=t("./transition_axes"),r.finalizeSubplots=function(t,e){var r,n,a,o=e._subplots,l=o.xaxis,s=o.yaxis,f=o.cartesian,d=f.concat(o.gl2d||[]),p={},h={};for(r=0;r<d.length;r++){var g=d[r].split("y");p[g[0]]=1,h["y"+g[1]]=1}for(r=0;r<l.length;r++)p[n=l[r]]||(a=(t[c.id2name(n)]||{}).anchor,u.idRegex.y.test(a)||(a="y"),f.push(n+a),d.push(n+a),h[a]||(h[a]=1,i.pushUnique(s,a)));for(r=0;r<s.length;r++)h[a=s[r]]||(n=(t[c.id2name(a)]||{}).anchor,u.idRegex.x.test(n)||(n="x"),f.push(n+a),d.push(n+a),p[n]||(p[n]=1,i.pushUnique(l,n)));if(!d.length){for(var y in n="",a="",t){if(u.attrRegex.test(y))"x"===y.charAt(0)?(!n||+y.substr(5)<+n.substr(5))&&(n=y):(!a||+y.substr(5)<+a.substr(5))&&(a=y)}n=n?c.name2id(n):"x",a=a?c.name2id(a):"y",l.push(n),s.push(a),f.push(n+a)}},r.plot=function(t,e,r,n){var a,i=t._fullLayout,o=i._subplots.cartesian,l=t.calcdata;if(null!==e){if(!Array.isArray(e))for(e=[],a=0;a<l.length;a++)e.push(a);for(a=0;a<o.length;a++){for(var s,c=o[a],u=i._plots[c],f=[],d=0;d<l.length;d++){var p=l[d],g=p[0].trace;g.xaxis+g.yaxis===c&&((-1!==e.indexOf(g.index)||g.carpet)&&(s&&s[0].trace.xaxis+s[0].trace.yaxis===c&&-1!==["tonextx","tonexty","tonext"].indexOf(g.fill)&&-1===f.indexOf(s)&&f.push(s),f.push(p)),s=p)}h(t,u,f,r,n)}}},r.clean=function(t,e,r,n){var a,i,o,l=n._plots||{},s=e._plots||{},u=n._subplots||{};if(n._hasOnlyLargeSploms&&!e._hasOnlyLargeSploms)for(o in l)(a=l[o]).plotgroup&&a.plotgroup.remove();var f=n._has&&n._has("gl"),d=e._has&&e._has("gl");if(f&&!d)for(o in l)(a=l[o])._scene&&a._scene.destroy();if(u.xaxis&&u.yaxis){var p=c.listIds({_fullLayout:n});for(i=0;i<p.length;i++){var h=p[i];e[c.id2name(h)]||n._infolayer.selectAll(".g-"+h+"title").remove()}}var g=n._has&&n._has("cartesian"),m=e._has&&e._has("cartesian");if(g&&!m)y(n._cartesianlayer.selectAll(".subplot"),n),n._defs.selectAll(".axesclip").remove(),delete n._axisConstraintGroups;else if(u.cartesian)for(i=0;i<u.cartesian.length;i++){var x=u.cartesian[i];if(!s[x]){var b="."+x+",."+x+"-x,."+x+"-y";n._cartesianlayer.selectAll(b).remove(),v(x,n)}}},r.drawFramework=function(t){var e=t._fullLayout,r=function(t){var e=t._fullLayout,r=[],n=[];for(var a in e._plots){var i=e._plots[a],o=i.xaxis._mainAxis,l=i.yaxis._mainAxis,s=o._id+l._id;s!==a&&e._plots[s]?(i.mainplot=s,i.mainplotinfo=e._plots[s],n.push(a)):(r.push(a),i.mainplot=void 0)}return r=r.concat(n)}(t),a=e._cartesianlayer.selectAll(".subplot").data(r,i.identity);a.enter().append("g").attr("class",function(t){return"subplot "+t}),a.order(),a.exit().call(y,e),a.each(function(r){var a=e._plots[r];(a.plotgroup=n.select(this),a.overlays=[],g(t,a),a.mainplot)&&e._plots[a.mainplot].overlays.push(a);a.draglayer=d(e._draggers,"g",r)})},r.rangePlot=function(t,e,r){g(t,e),h(t,e,r),o.style(t)},r.toSVG=function(t){var e=t._fullLayout._glimages,r=n.select(t).selectAll(".svg-container");r.filter(function(t,e){return e===r.size()-1}).selectAll(".gl-canvas-context, .gl-canvas-focus").each(function(){var t=this.toDataURL("image/png");e.append("svg:image").attr({xmlns:f.svg,"xlink:href":t,preserveAspectRatio:"none",x:0,y:0,width:this.width,height:this.height})})},r.updateFx=t("./graph_interact").updateFx},{"../../components/drawing":70,"../../constants/xmlns_namespaces":147,"../../lib":163,"../../registry":247,"../get_data":235,"../plots":239,"./attributes":205,"./axis_ids":210,"./constants":212,"./graph_interact":216,"./layout_attributes":219,"./layout_defaults":220,"./transition_axes":229,d3:10}],219:[function(t,e,r){"use strict";var n=t("../font_attributes"),a=t("../../components/color/attributes"),i=t("../../components/drawing/attributes").dash,o=t("../../lib/extend").extendFlat,l=t("../../plot_api/plot_template").templatedArray,s=t("./constants");e.exports={visible:{valType:"boolean",editType:"plot"},color:{valType:"color",dflt:a.defaultLine,editType:"ticks"},title:{valType:"string",editType:"ticks"},titlefont:n({editType:"ticks"}),type:{valType:"enumerated",values:["-","linear","log","date","category"],dflt:"-",editType:"calc",_noTemplating:!0},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0,editType:"calc",impliedEdits:{"range[0]":void 0,"range[1]":void 0}},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal",editType:"plot"},range:{valType:"info_array",items:[{valType:"any",editType:"axrange",impliedEdits:{"^autorange":!1}},{valType:"any",editType:"axrange",impliedEdits:{"^autorange":!1}}],editType:"axrange",impliedEdits:{autorange:!1}},fixedrange:{valType:"boolean",dflt:!1,editType:"calc"},scaleanchor:{valType:"enumerated",values:[s.idRegex.x.toString(),s.idRegex.y.toString()],editType:"plot"},scaleratio:{valType:"number",min:0,dflt:1,editType:"plot"},constrain:{valType:"enumerated",values:["range","domain"],dflt:"range",editType:"plot"},constraintoward:{valType:"enumerated",values:["left","center","right","top","middle","bottom"],editType:"plot"},tickmode:{valType:"enumerated",values:["auto","linear","array"],editType:"ticks",impliedEdits:{tick0:void 0,dtick:void 0}},nticks:{valType:"integer",min:0,dflt:0,editType:"ticks"},tick0:{valType:"any",editType:"ticks",impliedEdits:{tickmode:"linear"}},dtick:{valType:"any",editType:"ticks",impliedEdits:{tickmode:"linear"}},tickvals:{valType:"data_array",editType:"ticks"},ticktext:{valType:"data_array",editType:"ticks"},ticks:{valType:"enumerated",values:["outside","inside",""],editType:"ticks"},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1,editType:"ticks+layoutstyle"},ticklen:{valType:"number",min:0,dflt:5,editType:"ticks"},tickwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},tickcolor:{valType:"color",dflt:a.defaultLine,editType:"ticks"},showticklabels:{valType:"boolean",dflt:!0,editType:"ticks"},automargin:{valType:"boolean",dflt:!1,editType:"ticks"},showspikes:{valType:"boolean",dflt:!1,editType:"modebar"},spikecolor:{valType:"color",dflt:null,editType:"none"},spikethickness:{valType:"number",dflt:3,editType:"none"},spikedash:o({},i,{dflt:"dash",editType:"none"}),spikemode:{valType:"flaglist",flags:["toaxis","across","marker"],dflt:"toaxis",editType:"none"},spikesnap:{valType:"enumerated",values:["data","cursor"],dflt:"data",editType:"none"},tickfont:n({editType:"ticks"}),tickangle:{valType:"angle",dflt:"auto",editType:"ticks"},tickprefix:{valType:"string",dflt:"",editType:"ticks"},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},ticksuffix:{valType:"string",dflt:"",editType:"ticks"},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all",editType:"ticks"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B",editType:"ticks"},separatethousands:{valType:"boolean",dflt:!1,editType:"ticks"},tickformat:{valType:"string",dflt:"",editType:"ticks"},tickformatstops:l("tickformatstop",{enabled:{valType:"boolean",dflt:!0,editType:"ticks"},dtickrange:{valType:"info_array",items:[{valType:"any",editType:"ticks"},{valType:"any",editType:"ticks"}],editType:"ticks"},value:{valType:"string",dflt:"",editType:"ticks"},editType:"ticks"}),hoverformat:{valType:"string",dflt:"",editType:"none"},showline:{valType:"boolean",dflt:!1,editType:"layoutstyle"},linecolor:{valType:"color",dflt:a.defaultLine,editType:"layoutstyle"},linewidth:{valType:"number",min:0,dflt:1,editType:"ticks+layoutstyle"},showgrid:{valType:"boolean",editType:"ticks"},gridcolor:{valType:"color",dflt:a.lightLine,editType:"ticks"},gridwidth:{valType:"number",min:0,dflt:1,editType:"ticks"},zeroline:{valType:"boolean",editType:"ticks"},zerolinecolor:{valType:"color",dflt:a.defaultLine,editType:"ticks"},zerolinewidth:{valType:"number",dflt:1,editType:"ticks"},anchor:{valType:"enumerated",values:["free",s.idRegex.x.toString(),s.idRegex.y.toString()],editType:"plot"},side:{valType:"enumerated",values:["top","bottom","left","right"],editType:"plot"},overlaying:{valType:"enumerated",values:["free",s.idRegex.x.toString(),s.idRegex.y.toString()],editType:"plot"},layer:{valType:"enumerated",values:["above traces","below traces"],dflt:"above traces",editType:"plot"},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1,editType:"plot"},{valType:"number",min:0,max:1,editType:"plot"}],dflt:[0,1],editType:"plot"},position:{valType:"number",min:0,max:1,dflt:0,editType:"plot"},categoryorder:{valType:"enumerated",values:["trace","category ascending","category descending","array"],dflt:"trace",editType:"calc"},categoryarray:{valType:"data_array",editType:"calc"},editType:"calc",_deprecated:{autotick:{valType:"boolean",editType:"ticks"}}}},{"../../components/color/attributes":44,"../../components/drawing/attributes":69,"../../lib/extend":157,"../../plot_api/plot_template":197,"../font_attributes":233,"./constants":212}],220:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("../../components/color"),o=t("../../plot_api/plot_template"),l=t("../layout_attributes"),s=t("./layout_attributes"),c=t("./type_defaults"),u=t("./axis_defaults"),f=t("./constraint_defaults"),d=t("./position_defaults"),p=t("./axis_ids");e.exports=function(t,e,r){var h,g={},y={},v={},m={};for(h=0;h<r.length;h++){var x=r[h];if(n.traceIs(x,"cartesian")||n.traceIs(x,"gl2d")){var b=p.id2name(x.xaxis),_=p.id2name(x.yaxis);if(n.traceIs(x,"carpet")&&("carpet"!==x.type||x._cheater)||b&&(y[b]=1),"carpet"===x.type&&x._cheater&&b&&(g[b]=1),n.traceIs(x,"2dMap")&&(v[b]=!0,v[_]=!0),n.traceIs(x,"oriented"))m["h"===x.orientation?_:b]=!0}}var w=e._subplots,k=w.xaxis,M=w.yaxis,T=a.simpleMap(k,p.id2name),A=a.simpleMap(M,p.id2name),L=T.concat(A),C=i.background;k.length&&M.length&&(C=a.coerce(t,e,l,"plot_bgcolor"));var S,O,P,D,z=i.combine(C,e.paper_bgcolor);function E(t,e){return a.coerce(P,D,s,t,e)}function I(t,e){return a.coerce2(P,D,s,t,e)}function N(t){return"x"===t?M:k}var R={x:N("x"),y:N("y")};function F(e,r){for(var n="x"===e?T:A,a=[],i=0;i<n.length;i++){var o=n[i];o===r||(t[o]||{}).overlaying||a.push(p.name2id(o))}return a}for(h=0;h<L.length;h++){O=(S=L[h]).charAt(0),a.isPlainObject(t[S])||(t[S]={}),P=t[S],D=o.newContainer(e,S,O+"axis"),c(P,D,E,r,S);var j=F(O,S),B={letter:O,font:e.font,outerTicks:v[S],showGrid:!m[S],data:r,bgColor:z,calendar:e.calendar,automargin:!0,cheateronly:"x"===O&&g[S]&&!y[S]};u(P,D,E,B,e);var H=I("spikecolor"),q=I("spikethickness"),V=I("spikedash"),U=I("spikemode"),G=I("spikesnap");E("showspikes",!!(H||q||V||U||G))||(delete D.spikecolor,delete D.spikethickness,delete D.spikedash,delete D.spikemode,delete D.spikesnap);var Y={letter:O,counterAxes:R[O],overlayableAxes:j,grid:e.grid};d(P,D,E,Y),D._input=P}var X=n.getComponentMethod("rangeslider","handleDefaults"),Z=n.getComponentMethod("rangeselector","handleDefaults");for(h=0;h<T.length;h++)S=T[h],P=t[S],D=e[S],X(t,e,S),"date"===D.type&&Z(P,D,e,A,D.calendar),E("fixedrange");for(h=0;h<A.length;h++){S=A[h],P=t[S],D=e[S];var W=e[p.id2name(D.anchor)];E("fixedrange",W&&W.rangeslider&&W.rangeslider.visible)}e._axisConstraintGroups=[];var Q=R.x.concat(R.y);for(h=0;h<L.length;h++)O=(S=L[h]).charAt(0),P=t[S],D=e[S],f(P,D,E,Q,e)}},{"../../components/color":45,"../../lib":163,"../../plot_api/plot_template":197,"../../registry":247,"../layout_attributes":237,"./axis_defaults":209,"./axis_ids":210,"./constraint_defaults":213,"./layout_attributes":219,"./position_defaults":222,"./type_defaults":230}],221:[function(t,e,r){"use strict";var n=t("tinycolor2").mix,a=t("../../components/color/attributes").lightFraction,i=t("../../lib");e.exports=function(t,e,r,o){var l=(o=o||{}).dfltColor;function s(r,n){return i.coerce2(t,e,o.attributes,r,n)}var c=s("linecolor",l),u=s("linewidth");r("showline",o.showLine||!!c||!!u)||(delete e.linecolor,delete e.linewidth);var f=s("gridcolor",n(l,o.bgColor,o.blend||a).toRgbString()),d=s("gridwidth");if(r("showgrid",o.showGrid||!!f||!!d)||(delete e.gridcolor,delete e.gridwidth),!o.noZeroLine){var p=s("zerolinecolor",l),h=s("zerolinewidth");r("zeroline",o.showGrid||!!p||!!h)||(delete e.zerolinecolor,delete e.zerolinewidth)}}},{"../../components/color/attributes":44,"../../lib":163,tinycolor2:28}],222:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib");e.exports=function(t,e,r,i){var o,l,s,c,u=i.counterAxes||[],f=i.overlayableAxes||[],d=i.letter,p=i.grid;p&&(l=p._domains[d][p._axisMap[e._id]],o=p._anchors[e._id],l&&(s=p[d+"side"].split(" ")[0],c=p.domain[d]["right"===s||"top"===s?1:0])),l=l||[0,1],o=o||(n(t.position)?"free":u[0]||"free"),s=s||("x"===d?"bottom":"left"),c=c||0,"free"===a.coerce(t,e,{anchor:{valType:"enumerated",values:["free"].concat(u),dflt:o}},"anchor")&&r("position",c),a.coerce(t,e,{side:{valType:"enumerated",values:"x"===d?["bottom","top"]:["left","right"],dflt:s}},"side");var h=!1;if(f.length&&(h=a.coerce(t,e,{overlaying:{valType:"enumerated",values:[!1].concat(f),dflt:!1}},"overlaying")),!h){var g=r("domain",l);g[0]>g[1]-.01&&(e.domain=l),a.noneOrAll(t.domain,e.domain,l)}return r("layer"),e}},{"../../lib":163,"fast-isnumeric":13}],223:[function(t,e,r){"use strict";var n=t("../../constants/alignment").FROM_BL;e.exports=function(t,e,r){void 0===r&&(r=n[t.constraintoward||"center"]);var a=[t.r2l(t.range[0]),t.r2l(t.range[1])],i=a[0]+(a[1]-a[0])*r;t.range=t._input.range=[t.l2r(i+(a[0]-i)*e),t.l2r(i+(a[1]-i)*e)]}},{"../../constants/alignment":143}],224:[function(t,e,r){"use strict";var n=t("polybooljs"),a=t("../../registry"),i=t("../../components/color"),o=t("../../components/fx"),l=t("../../lib/polygon"),s=t("../../lib/throttle"),c=t("../../components/fx/helpers").makeEventData,u=t("./axis_ids").getFromId,f=t("../sort_modules").sortModules,d=t("./constants"),p=d.MINSELECT,h=l.filter,g=l.tester,y=l.multitester;function v(t){return t._id}function m(t,e,r){var n,i,o,l;if(r){var s=r.points||[];for(n=0;n<e.length;n++)(l=e[n].cd[0].trace).selectedpoints=[],l._input.selectedpoints=[];for(n=0;n<s.length;n++){var c=s[n],u=c.data,d=c.fullData;c.pointIndices?([].push.apply(u.selectedpoints,c.pointIndices),[].push.apply(d.selectedpoints,c.pointIndices)):(u.selectedpoints.push(c.pointIndex),d.selectedpoints.push(c.pointIndex))}}else for(n=0;n<e.length;n++)delete(l=e[n].cd[0].trace).selectedpoints,delete l._input.selectedpoints;var p={};for(n=0;n<e.length;n++){var h=(o=e[n])._module.name;p[h]?p[h].push(o):p[h]=[o]}var g=Object.keys(p).sort(f);for(n=0;n<g.length;n++){var y=p[g[n]],v=y.length,m=y[0],x=m.cd[0].trace,b=m._module,_=b.styleOnSelect||b.style;if(a.traceIs(x,"regl")){var w=new Array(v);for(i=0;i<v;i++)w[i]=y[i].cd;_(t,w)}else for(i=0;i<v;i++)_(t,y[i].cd)}}function x(t,e){if(Array.isArray(t))for(var r=e.cd,n=e.cd[0].trace,a=0;a<t.length;a++)t[a]=c(t[a],n,r);return t}function b(t){t.selectAll(".select-outline").remove()}e.exports={prepSelect:function(t,e,r,a,l){var c,f,_,w,k,M,T,A,L,C=a.gd,S=C._fullLayout,O=S._zoomlayer,P=a.element.getBoundingClientRect(),D=a.plotinfo,z=D.xaxis._offset,E=D.yaxis._offset,I=e-P.left,N=r-P.top,R=I,F=N,j="M"+I+","+N,B=a.xaxes[0]._length,H=a.yaxes[0]._length,q=a.xaxes.map(v),V=a.yaxes.map(v),U=a.xaxes.concat(a.yaxes),G=t.altKey,Y=S._lastSelectedSubplot&&S._lastSelectedSubplot===D.id;Y&&(t.shiftKey||t.altKey)&&D.selection&&D.selection.polygons&&!a.polygons?(a.polygons=D.selection.polygons,a.mergedPolygons=D.selection.mergedPolygons):(!t.shiftKey&&!t.altKey||(t.shiftKey||t.altKey)&&!D.selection)&&(D.selection={},D.selection.polygons=a.polygons=[],D.selection.mergedPolygons=a.mergedPolygons=[]),Y||(b(O),S._lastSelectedSubplot=D.id),"lasso"===l&&(c=h([[I,N]],d.BENDPX));var X=O.selectAll("path.select-outline-"+D.id).data([1,2]);X.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t+" select-outline-"+D.id}).attr("transform","translate("+z+", "+E+")").attr("d",j+"Z");var Z,W=O.append("path").attr("class","zoombox-corners").style({fill:i.background,stroke:i.defaultLine,"stroke-width":1}).attr("transform","translate("+z+", "+E+")").attr("d","M0,0Z"),Q=[],J=S._uid+d.SELECTID,$=[];for(k=0;k<C.calcdata.length;k++)if(!0===(T=(M=C.calcdata[k])[0].trace).visible&&T._module&&T._module.selectPoints)if(a.subplot)T.subplot!==a.subplot&&T.geo!==a.subplot||Q.push({_module:T._module,cd:M,xaxis:a.xaxes[0],yaxis:a.yaxes[0]});else if("splom"===T.type&&T._xaxes[q[0]]&&T._yaxes[V[0]])Q.push({_module:T._module,cd:M,xaxis:a.xaxes[0],yaxis:a.yaxes[0]});else{if(-1===q.indexOf(T.xaxis))continue;if(-1===V.indexOf(T.yaxis))continue;Q.push({_module:T._module,cd:M,xaxis:u(C,T.xaxis),yaxis:u(C,T.yaxis)})}function K(t){var e="y"===t._id.charAt(0)?1:0;return function(r){return t.p2d(r[e])}}function tt(t,e){return t-e}Z=D.fillRangeItems?D.fillRangeItems:"select"===l?function(t,e){var r=t.range={};for(k=0;k<U.length;k++){var n=U[k],a=n._id.charAt(0);r[n._id]=[n.p2d(e[a+"min"]),n.p2d(e[a+"max"])].sort(tt)}}:function(t,e,r){var n=t.lassoPoints={};for(k=0;k<U.length;k++){var a=U[k];n[a._id]=r.filtered.map(K(a))}},a.moveFn=function(t,e){R=Math.max(0,Math.min(B,t+I)),F=Math.max(0,Math.min(H,e+N));var r=Math.abs(R-I),i=Math.abs(F-N);if("select"===l){var o=S.selectdirection;"h"===(o="any"===S.selectdirection?i<Math.min(.6*r,p)?"h":r<Math.min(.6*i,p)?"v":"d":S.selectdirection)?((w=[[I,0],[I,H],[R,H],[R,0]]).xmin=Math.min(I,R),w.xmax=Math.max(I,R),w.ymin=Math.min(0,H),w.ymax=Math.max(0,H),W.attr("d","M"+w.xmin+","+(N-p)+"h-4v"+2*p+"h4ZM"+(w.xmax-1)+","+(N-p)+"h4v"+2*p+"h-4Z")):"v"===o?((w=[[0,N],[0,F],[B,F],[B,N]]).xmin=Math.min(0,B),w.xmax=Math.max(0,B),w.ymin=Math.min(N,F),w.ymax=Math.max(N,F),W.attr("d","M"+(I-p)+","+w.ymin+"v-4h"+2*p+"v4ZM"+(I-p)+","+(w.ymax-1)+"v4h"+2*p+"v-4Z")):"d"===o&&((w=[[I,N],[I,F],[R,F],[R,N]]).xmin=Math.min(I,R),w.xmax=Math.max(I,R),w.ymin=Math.min(N,F),w.ymax=Math.max(N,F),W.attr("d","M0,0Z"))}else"lasso"===l&&(c.addPt([R,F]),w=c.filtered);a.polygons&&a.polygons.length?(_=function(t,e,r){return r?n.difference({regions:t,inverted:!1},{regions:[e],inverted:!1}).regions:n.union({regions:t,inverted:!1},{regions:[e],inverted:!1}).regions}(a.mergedPolygons,w,G),w.subtract=G,f=y(a.polygons.concat([w]))):(_=[w],f=g(w));var u=[];for(k=0;k<_.length;k++){var h=_[k];u.push(h.join("L")+"L"+h[0])}X.attr("d","M"+u.join("M")+"Z"),s.throttle(J,d.SELECTDELAY,function(){$=[];var t,e,r=[];for(k=0;k<Q.length;k++)if(e=(A=Q[k])._module.selectPoints(A,f),r.push(e),t=x(e,A),$.length)for(var n=0;n<t.length;n++)$.push(t[n]);else $=t;m(C,Q,L={points:$}),Z(L,w,c),a.gd.emit("plotly_selecting",L)})},a.clickFn=function(t,e){W.remove(),s.done(J).then(function(){if(s.clear(J),2===t){for(X.remove(),k=0;k<Q.length;k++)(A=Q[k])._module.selectPoints(A,!1);m(C,Q),C.emit("plotly_deselect",null)}else C.emit("plotly_selected",void 0);o.click(C,e)})},a.doneFn=function(){W.remove(),s.done(J).then(function(){s.clear(J),a.gd.emit("plotly_selected",L),w&&a.polygons&&(w.subtract=G,a.polygons.push(w),a.mergedPolygons.length=0,[].push.apply(a.mergedPolygons,_))})}},clearSelect:b}},{"../../components/color":45,"../../components/fx":87,"../../components/fx/helpers":84,"../../lib/polygon":175,"../../lib/throttle":185,"../../registry":247,"../sort_modules":246,"./axis_ids":210,"./constants":212,polybooljs:19}],225:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../../lib"),o=i.cleanNumber,l=i.ms2DateTime,s=i.dateTime2ms,c=i.ensureNumber,u=t("../../constants/numerical"),f=u.FP_SAFE,d=u.BADNUM,p=t("./constants"),h=t("./axis_ids");function g(t){return Math.pow(10,t)}e.exports=function(t,e){e=e||{};var r=(t._id||"x").charAt(0),u=10;function y(e,r){if(e>0)return Math.log(e)/Math.LN10;if(e<=0&&r&&t.range&&2===t.range.length){var n=t.range[0],a=t.range[1];return.5*(n+a-3*u*Math.abs(n-a))}return d}function v(e,r,n){var i=s(e,n||t.calendar);if(i===d){if(!a(e))return d;i=s(new Date(+e))}return i}function m(e,r,n){return l(e,r,n||t.calendar)}function x(e){return t._categories[Math.round(e)]}function b(e){if(t._categoriesMap){var r=t._categoriesMap[e];if(void 0!==r)return r}if(a(e))return+e}function _(e){return a(e)?n.round(t._b+t._m*e,2):d}function w(e){return(e-t._b)/t._m}t.c2l="log"===t.type?y:c,t.l2c="log"===t.type?g:c,t.l2p=_,t.p2l=w,t.c2p="log"===t.type?function(t,e){return _(y(t,e))}:_,t.p2c="log"===t.type?function(t){return g(w(t))}:w,-1!==["linear","-"].indexOf(t.type)?(t.d2r=t.r2d=t.d2c=t.r2c=t.d2l=t.r2l=o,t.c2d=t.c2r=t.l2d=t.l2r=c,t.d2p=t.r2p=function(e){return t.l2p(o(e))},t.p2d=t.p2r=w,t.cleanPos=c):"log"===t.type?(t.d2r=t.d2l=function(t,e){return y(o(t),e)},t.r2d=t.r2c=function(t){return g(o(t))},t.d2c=t.r2l=o,t.c2d=t.l2r=c,t.c2r=y,t.l2d=g,t.d2p=function(e,r){return t.l2p(t.d2r(e,r))},t.p2d=function(t){return g(w(t))},t.r2p=function(e){return t.l2p(o(e))},t.p2r=w,t.cleanPos=c):"date"===t.type?(t.d2r=t.r2d=i.identity,t.d2c=t.r2c=t.d2l=t.r2l=v,t.c2d=t.c2r=t.l2d=t.l2r=m,t.d2p=t.r2p=function(e,r,n){return t.l2p(v(e,0,n))},t.p2d=t.p2r=function(t,e,r){return m(w(t),e,r)},t.cleanPos=function(e){return i.cleanDate(e,d,t.calendar)}):"category"===t.type&&(t.d2c=t.d2l=function(e){if(null!=e){if(void 0===t._categoriesMap&&(t._categoriesMap={}),void 0!==t._categoriesMap[e])return t._categoriesMap[e];t._categories.push(e);var r=t._categories.length-1;return t._categoriesMap[e]=r,r}return d},t.r2d=t.c2d=t.l2d=x,t.d2r=t.d2l_noadd=b,t.r2c=function(e){var r=b(e);return void 0!==r?r:t.fraction2r(.5)},t.l2r=t.c2r=c,t.r2l=b,t.d2p=function(e){return t.l2p(t.r2c(e))},t.p2d=function(t){return x(w(t))},t.r2p=t.d2p,t.p2r=w,t.cleanPos=function(t){return"string"==typeof t&&""!==t?t:c(t)}),t.fraction2r=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return t.l2r(r+e*(n-r))},t.r2fraction=function(e){var r=t.r2l(t.range[0]),n=t.r2l(t.range[1]);return(t.r2l(e)-r)/(n-r)},t.cleanRange=function(e,n){n||(n={}),e||(e="range");var o,l,s=i.nestedProperty(t,e).get();if(l=(l="date"===t.type?i.dfltRange(t.calendar):"y"===r?p.DFLTRANGEY:n.dfltRange||p.DFLTRANGEX).slice(),s&&2===s.length)for("date"===t.type&&(s[0]=i.cleanDate(s[0],d,t.calendar),s[1]=i.cleanDate(s[1],d,t.calendar)),o=0;o<2;o++)if("date"===t.type){if(!i.isDateTime(s[o],t.calendar)){t[e]=l;break}if(t.r2l(s[0])===t.r2l(s[1])){var c=i.constrain(t.r2l(s[0]),i.MIN_MS+1e3,i.MAX_MS-1e3);s[0]=t.l2r(c-1e3),s[1]=t.l2r(c+1e3);break}}else{if(!a(s[o])){if(!a(s[1-o])){t[e]=l;break}s[o]=s[1-o]*(o?10:.1)}if(s[o]<-f?s[o]=-f:s[o]>f&&(s[o]=f),s[0]===s[1]){var u=Math.max(1,Math.abs(1e-6*s[0]));s[0]-=u,s[1]+=u}}else i.nestedProperty(t,e).set(l)},t.setScale=function(n){var a=e._size;if(t._categories||(t._categories=[]),t._categoriesMap||(t._categoriesMap={}),t.overlaying){var i=h.getFromId({_fullLayout:e},t.overlaying);t.domain=i.domain}var o=n&&t._r?"_r":"range",l=t.calendar;t.cleanRange(o);var s=t.r2l(t[o][0],l),c=t.r2l(t[o][1],l);if("y"===r?(t._offset=a.t+(1-t.domain[1])*a.h,t._length=a.h*(t.domain[1]-t.domain[0]),t._m=t._length/(s-c),t._b=-t._m*c):(t._offset=a.l+t.domain[0]*a.w,t._length=a.w*(t.domain[1]-t.domain[0]),t._m=t._length/(c-s),t._b=-t._m*s),!isFinite(t._m)||!isFinite(t._b))throw e._replotting=!1,new Error("Something went wrong with axis scaling")},t.makeCalcdata=function(e,r){var n,a,o,l,s=t.type,c="date"===s&&e[r+"calendar"];if(r in e){if(n=e[r],l=e._length||n.length,i.isTypedArray(n)&&("linear"===s||"log"===s)){if(l===n.length)return n;if(n.subarray)return n.subarray(0,l)}for(a=new Array(l),o=0;o<l;o++)a[o]=t.d2c(n[o],0,c)}else{var u=r+"0"in e?t.d2c(e[r+"0"],0,c):0,f=e["d"+r]?Number(e["d"+r]):1;for(n=e[{x:"y",y:"x"}[r]],l=e._length||n.length,a=new Array(l),o=0;o<l;o++)a[o]=u+o*f}return a},t.isValidRange=function(e){return Array.isArray(e)&&2===e.length&&a(t.r2l(e[0]))&&a(t.r2l(e[1]))},t.isPtWithinRange=function(e,n){var a=t.c2l(e[r],null,n),i=t.r2l(t.range[0]),o=t.r2l(t.range[1]);return i<o?i<=a&&a<=o:o<=a&&a<=i},t.clearCalc=function(){t._min=[],t._max=[],t._categories=(t._initialCategories||[]).slice(),t._categoriesMap={};for(var e=0;e<t._categories.length;e++)t._categoriesMap[t._categories[e]]=e};var k=e._d3locale;"date"===t.type&&(t._dateFormat=k?k.timeFormat.utc:n.time.format.utc,t._extraFormat=e._extraFormat),t._separators=e.separators,t._numFormat=k?k.numberFormat:n.format,delete t._minDtick,delete t._forceTick0}},{"../../constants/numerical":145,"../../lib":163,"./axis_ids":210,"./constants":212,d3:10,"fast-isnumeric":13}],226:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./layout_attributes"),i=t("../array_container_defaults");function o(t,e){function r(r,i){return n.coerce(t,e,a.tickformatstops,r,i)}r("enabled")&&(r("dtickrange"),r("value"))}e.exports=function(t,e,r,l,s){var c=function(t){var e=["showexponent","showtickprefix","showticksuffix"].filter(function(e){return void 0!==t[e]});if(e.every(function(r){return t[r]===t[e[0]]})||1===e.length)return t[e[0]]}(t);if(r("tickprefix")&&r("showtickprefix",c),r("ticksuffix",s.tickSuffixDflt)&&r("showticksuffix",c),r("showticklabels")){var u=s.font||{},f=e.color!==a.color.dflt?e.color:u.color;if(n.coerceFont(r,"tickfont",{family:u.family,size:u.size,color:f}),r("tickangle"),"category"!==l){var d=r("tickformat"),p=t.tickformatstops;Array.isArray(p)&&p.length&&i(t,e,{name:"tickformatstops",inclusionAttr:"enabled",handleItemDefaults:o}),d||"date"===l||(r("showexponent",c),r("exponentformat"),r("separatethousands"))}}}},{"../../lib":163,"../array_container_defaults":203,"./layout_attributes":219}],227:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./layout_attributes");e.exports=function(t,e,r,i){var o=n.coerce2(t,e,a,"ticklen"),l=n.coerce2(t,e,a,"tickwidth"),s=n.coerce2(t,e,a,"tickcolor",e.color);r("ticks",i.outerTicks||o||l||s?"outside":"")||(delete e.ticklen,delete e.tickwidth,delete e.tickcolor)}},{"../../lib":163,"./layout_attributes":219}],228:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../../constants/numerical").ONEDAY;e.exports=function(t,e,r,o){var l;"array"!==t.tickmode||"log"!==o&&"date"!==o?l=r("tickmode",Array.isArray(t.tickvals)?"array":t.dtick?"linear":"auto"):l=e.tickmode="auto";if("auto"===l)r("nticks");else if("linear"===l){var s="date"===o?i:1,c=r("dtick",s);if(n(c))e.dtick=c>0?Number(c):s;else if("string"!=typeof c)e.dtick=s;else{var u=c.charAt(0),f=c.substr(1);((f=n(f)?Number(f):0)<=0||!("date"===o&&"M"===u&&f===Math.round(f)||"log"===o&&"L"===u||"log"===o&&"D"===u&&(1===f||2===f)))&&(e.dtick=s)}var d="date"===o?a.dateTick0(e.calendar):0,p=r("tick0",d);"date"===o?e.tick0=a.cleanDate(p,d):n(p)&&"D1"!==c&&"D2"!==c?e.tick0=Number(p):e.tick0=d}else{void 0===r("tickvals")?e.tickmode="auto":r("ticktext")}}},{"../../constants/numerical":145,"../../lib":163,"fast-isnumeric":13}],229:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../components/drawing"),o=t("./axes"),l=t("./constants").attrRegex;e.exports=function(t,e,r,s){var c=t._fullLayout,u=[];var f,d,p,h,g=function(t){var e,r,n,a,i={};for(e in t)if((r=e.split("."))[0].match(l)){var o=e.charAt(0),s=r[0];if(n=c[s],a={},Array.isArray(t[e])?a.to=t[e].slice(0):Array.isArray(t[e].range)&&(a.to=t[e].range.slice(0)),!a.to)continue;a.axisName=s,a.length=n._length,u.push(o),i[o]=a}return i}(e),y=Object.keys(g),v=function(t,e,r){var n,a,i,o=t._plots,l=[];for(n in o){var s=o[n];if(-1===l.indexOf(s)){var c=s.xaxis._id,u=s.yaxis._id,f=s.xaxis.range,d=s.yaxis.range;s.xaxis._r=s.xaxis.range.slice(),s.yaxis._r=s.yaxis.range.slice(),a=r[c]?r[c].to:f,i=r[u]?r[u].to:d,f[0]===a[0]&&f[1]===a[1]&&d[0]===i[0]&&d[1]===i[1]||-1===e.indexOf(c)&&-1===e.indexOf(u)||l.push(s)}}return l}(c,y,g);if(!v.length)return function(){function e(e,r,n){for(var a=0;a<e.length;a++)if(r(t,a),n)return}e(c.annotations||[],a.getComponentMethod("annotations","drawOne")),e(c.shapes||[],a.getComponentMethod("shapes","drawOne")),e(c.images||[],a.getComponentMethod("images","draw"),!0)}(),!1;function m(t){var e=t.xaxis,r=t.yaxis;c._defs.select("#"+t.clipId+"> rect").call(i.setTranslate,0,0).call(i.setScale,1,1),t.plot.call(i.setTranslate,e._offset,r._offset).call(i.setScale,1,1);var n=t.plot.selectAll(".scatterlayer .trace");n.selectAll(".point").call(i.setPointGroupScale,1,1),n.selectAll(".textpoint").call(i.setTextPointsScale,1,1),n.call(i.hideOutsideRangePoints,t)}function x(e,r){var n,l,s,u=g[e.xaxis._id],f=g[e.yaxis._id],d=[];if(u){l=(n=t._fullLayout[u.axisName])._r,s=u.to,d[0]=(l[0]*(1-r)+r*s[0]-l[0])/(l[1]-l[0])*e.xaxis._length;var p=l[1]-l[0],h=s[1]-s[0];n.range[0]=l[0]*(1-r)+r*s[0],n.range[1]=l[1]*(1-r)+r*s[1],d[2]=e.xaxis._length*(1-r+r*h/p)}else d[0]=0,d[2]=e.xaxis._length;if(f){l=(n=t._fullLayout[f.axisName])._r,s=f.to,d[1]=(l[1]*(1-r)+r*s[1]-l[1])/(l[0]-l[1])*e.yaxis._length;var y=l[1]-l[0],v=s[1]-s[0];n.range[0]=l[0]*(1-r)+r*s[0],n.range[1]=l[1]*(1-r)+r*s[1],d[3]=e.yaxis._length*(1-r+r*v/y)}else d[1]=0,d[3]=e.yaxis._length;!function(e,r){var n,i=[];for(i=[e._id,r._id],n=0;n<i.length;n++)o.doTicksSingle(t,i[n],!0);function l(e,r,a){for(n=0;n<e.length;n++){var o=e[n];if(-1===i.indexOf(o.xref)&&-1===i.indexOf(o.yref)||r(t,n),a)return}}l(c.annotations||[],a.getComponentMethod("annotations","drawOne")),l(c.shapes||[],a.getComponentMethod("shapes","drawOne")),l(c.images||[],a.getComponentMethod("images","draw"),!0)}(e.xaxis,e.yaxis);var m=e.xaxis,x=e.yaxis,b=!!u,_=!!f,w=b?m._length/d[2]:1,k=_?x._length/d[3]:1,M=b?d[0]:0,T=_?d[1]:0,A=b?d[0]/d[2]*m._length:0,L=_?d[1]/d[3]*x._length:0,C=m._offset-A,S=x._offset-L;e.clipRect.call(i.setTranslate,M,T).call(i.setScale,1/w,1/k),e.plot.call(i.setTranslate,C,S).call(i.setScale,w,k),i.setPointGroupScale(e.zoomScalePts,1/w,1/k),i.setTextPointsScale(e.zoomScaleTxt,1/w,1/k)}s&&(f=s());var b=n.ease(r.easing);return t._transitionData._interruptCallbacks.push(function(){return window.cancelAnimationFrame(h),h=null,function(){for(var e={},r=0;r<y.length;r++){var n=t._fullLayout[y[r]+"axis"];e[n._name+".range[0]"]=n.range[0],e[n._name+".range[1]"]=n.range[1],n.range=n._r.slice()}return a.call("relayout",t,e).then(function(){for(var t=0;t<v.length;t++)m(v[t])})}()}),d=Date.now(),h=window.requestAnimationFrame(function e(){p=Date.now();for(var n=Math.min(1,(p-d)/r.duration),i=b(n),o=0;o<v.length;o++)x(v[o],i);p-d>r.duration?(function(){for(var e={},r=0;r<y.length;r++){var n=t._fullLayout[g[y[r]].axisName],i=g[y[r]].to;e[n._name+".range[0]"]=i[0],e[n._name+".range[1]"]=i[1],n.range=i.slice()}f&&f(),a.call("relayout",t,e).then(function(){for(var t=0;t<v.length;t++)m(v[t])})}(),h=window.cancelAnimationFrame(e)):h=window.requestAnimationFrame(e)}),Promise.resolve()}},{"../../components/drawing":70,"../../registry":247,"./axes":207,"./constants":212,d3:10}],230:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("./axis_autotype"),i=t("./axis_ids").name2id;function o(t){return{v:"x",h:"y"}[t.orientation||"v"]}function l(t,e){var r=o(t),a=n.traceIs(t,"box-violin"),i=n.traceIs(t._fullInput||{},"candlestick");return a&&!i&&e===r&&void 0===t[r]&&void 0===t[r+"0"]}e.exports=function(t,e,r,s,c){c&&(e._name=c,e._id=i(c)),"-"===r("type")&&(!function(t,e){if("-"!==t.type)return;var r=t._id,i=r.charAt(0);-1!==r.indexOf("scene")&&(r=i);var s=function(t,e,r){for(var n=0;n<t.length;n++){var a=t[n];if("splom"===a.type&&a._length>0&&a["_"+r+"axes"][e])return a;if((a[r+"axis"]||r)===e){if(l(a,r))return a;if((a[r]||[]).length||a[r+"0"])return a}}}(e,r,i);if(!s)return;if("histogram"===s.type&&i==={v:"y",h:"x"}[s.orientation||"v"])return void(t.type="linear");var c,u=i+"calendar",f=s[u];if(l(s,i)){var d=o(s),p=[];for(c=0;c<e.length;c++){var h=e[c];n.traceIs(h,"box-violin")&&(h[i+"axis"]||i)===r&&(void 0!==h[d]?p.push(h[d][0]):void 0!==h.name?p.push(h.name):p.push("text"),h[u]!==f&&(f=void 0))}t.type=a(p,f)}else if("splom"===s.type){var g=s.dimensions;for(c=0;c<g.length;c++){var y=g[c];if(y.visible){t.type=a(y.values,f);break}}}else t.type=a(s[i]||[s[i+"0"]],f)}(e,s),"-"===e.type?e.type="linear":t.type=e.type)}},{"../../registry":247,"./axis_autotype":208,"./axis_ids":210}],231:[function(t,e,r){"use strict";var n=t("../registry"),a=t("../lib");function i(t,e,r){var n,i,o,l=!1;if("data"===e.type)n=t._fullData[null!==e.traces?e.traces[0]:0];else{if("layout"!==e.type)return!1;n=t._fullLayout}return i=a.nestedProperty(n,e.prop).get(),(o=r[e.type]=r[e.type]||{}).hasOwnProperty(e.prop)&&o[e.prop]!==i&&(l=!0),o[e.prop]=i,{changed:l,value:i}}function o(t,e){var r=[],n=e[0],i={};if("string"==typeof n)i[n]=e[1];else{if(!a.isPlainObject(n))return r;i=n}return s(i,function(t,e,n){r.push({type:"layout",prop:t,value:n})},"",0),r}function l(t,e){var r,n,i,o,l=[];if(n=e[0],i=e[1],r=e[2],o={},"string"==typeof n)o[n]=i;else{if(!a.isPlainObject(n))return l;o=n,void 0===r&&(r=i)}return void 0===r&&(r=null),s(o,function(e,n,a){var i;if(Array.isArray(a)){var o=Math.min(a.length,t.data.length);r&&(o=Math.min(o,r.length)),i=[];for(var s=0;s<o;s++)i[s]=r?r[s]:s}else i=r?r.slice(0):null;if(null===i)Array.isArray(a)&&(a=a[0]);else if(Array.isArray(i)){if(!Array.isArray(a)){var c=a;a=[];for(var u=0;u<i.length;u++)a[u]=c}a.length=Math.min(i.length,a.length)}l.push({type:"data",prop:e,traces:i,value:a})},"",0),l}function s(t,e,r,n){Object.keys(t).forEach(function(i){var o=t[i];if("_"!==i[0]){var l=r+(n>0?".":"")+i;a.isPlainObject(o)?s(o,e,l,n+1):e(l,i,o)}})}r.manageCommandObserver=function(t,e,n,o){var l={},s=!0;e&&e._commandObserver&&(l=e._commandObserver),l.cache||(l.cache={}),l.lookupTable={};var c=r.hasSimpleAPICommandBindings(t,n,l.lookupTable);if(e&&e._commandObserver){if(c)return l;if(e._commandObserver.remove)return e._commandObserver.remove(),e._commandObserver=null,l}if(c){i(t,c,l.cache),l.check=function(){if(s){var e=i(t,c,l.cache);return e.changed&&o&&void 0!==l.lookupTable[e.value]&&(l.disable(),Promise.resolve(o({value:e.value,type:c.type,prop:c.prop,traces:c.traces,index:l.lookupTable[e.value]})).then(l.enable,l.enable)),e.changed}};for(var u=["plotly_relayout","plotly_redraw","plotly_restyle","plotly_update","plotly_animatingframe","plotly_afterplot"],f=0;f<u.length;f++)t._internalOn(u[f],l.check);l.remove=function(){for(var e=0;e<u.length;e++)t._removeInternalListener(u[e],l.check)}}else a.log("Unable to automatically bind plot updates to API command"),l.lookupTable={},l.remove=function(){};return l.disable=function(){s=!1},l.enable=function(){s=!0},e&&(e._commandObserver=l),l},r.hasSimpleAPICommandBindings=function(t,e,n){var a,i,o=e.length;for(a=0;a<o;a++){var l,s=e[a],c=s.method,u=s.args;if(Array.isArray(u)||(u=[]),!c)return!1;var f=r.computeAPICommandBindings(t,c,u);if(1!==f.length)return!1;if(i){if((l=f[0]).type!==i.type)return!1;if(l.prop!==i.prop)return!1;if(Array.isArray(i.traces)){if(!Array.isArray(l.traces))return!1;l.traces.sort();for(var d=0;d<i.traces.length;d++)if(i.traces[d]!==l.traces[d])return!1}else if(l.prop!==i.prop)return!1}else i=f[0],Array.isArray(i.traces)&&i.traces.sort();var p=(l=f[0]).value;if(Array.isArray(p)){if(1!==p.length)return!1;p=p[0]}n&&(n[p]=a)}return i},r.executeAPICommand=function(t,e,r){if("skip"===e)return Promise.resolve();var i=n.apiMethodRegistry[e],o=[t];Array.isArray(r)||(r=[]);for(var l=0;l<r.length;l++)o.push(r[l]);return i.apply(null,o).catch(function(t){return a.warn("API call to Plotly."+e+" rejected.",t),Promise.reject(t)})},r.computeAPICommandBindings=function(t,e,r){var n;switch(Array.isArray(r)||(r=[]),e){case"restyle":n=l(t,r);break;case"relayout":n=o(t,r);break;case"update":n=l(t,[r[0],r[2]]).concat(o(t,[r[1]]));break;case"animate":n=function(t,e){return Array.isArray(e[0])&&1===e[0].length&&-1!==["string","number"].indexOf(typeof e[0][0])?[{type:"layout",prop:"_currentFrame",value:e[0][0].toString()}]:[]}(0,r);break;default:n=[]}return n}},{"../lib":163,"../registry":247}],232:[function(t,e,r){"use strict";var n=t("../lib/extend").extendFlat;r.attributes=function(t,e){e=e||{};var r={valType:"info_array",editType:(t=t||{}).editType,items:[{valType:"number",min:0,max:1,editType:t.editType},{valType:"number",min:0,max:1,editType:t.editType}],dflt:[0,1]},a=(t.name&&t.name,t.trace,e.description&&e.description,{x:n({},r,{}),y:n({},r,{}),editType:t.editType});return t.noGridCell||(a.row={valType:"integer",min:0,dflt:0,editType:t.editType},a.column={valType:"integer",min:0,dflt:0,editType:t.editType}),a},r.defaults=function(t,e,r,n){var a=n&&n.x||[0,1],i=n&&n.y||[0,1],o=e.grid;if(o){var l=r("domain.column");void 0!==l&&(l<o.columns?a=o._domains.x[l]:delete t.domain.column);var s=r("domain.row");void 0!==s&&(s<o.rows?i=o._domains.y[s]:delete t.domain.row)}r("domain.x",a),r("domain.y",i)}},{"../lib/extend":157}],233:[function(t,e,r){"use strict";e.exports=function(t){var e=t.editType,r=t.colorEditType;void 0===r&&(r=e);var n={family:{valType:"string",noBlank:!0,strict:!0,editType:e},size:{valType:"number",min:1,editType:e},color:{valType:"color",editType:r},editType:e};return t.arrayOk&&(n.family.arrayOk=!0,n.size.arrayOk=!0,n.color.arrayOk=!0),n}},{}],234:[function(t,e,r){"use strict";e.exports={_isLinkedToArray:"frames_entry",group:{valType:"string"},name:{valType:"string"},traces:{valType:"any"},baseframe:{valType:"string"},data:{valType:"any"},layout:{valType:"any"}}},{}],235:[function(t,e,r){"use strict";var n=t("../registry"),a=t("./cartesian/constants").SUBPLOT_PATTERN;r.getSubplotCalcData=function(t,e,r){var a=n.subplotsRegistry[e];if(!a)return[];for(var i=a.attr,o=[],l=0;l<t.length;l++){var s=t[l];s[0].trace[i]===r&&o.push(s)}return o},r.getModuleCalcData=function(t,e){var r,a=[],i=[];if(!(r="string"==typeof e?n.getModule(e).plot:"function"==typeof e?e:e.plot))return[a,t];for(var o=0;o<t.length;o++){var l=t[o],s=l[0].trace;!0===s.visible&&(s._module.plot===r?a.push(l):i.push(l))}return[a,i]},r.getSubplotData=function(t,e,r){if(!n.subplotsRegistry[e])return[];var i,o,l,s=n.subplotsRegistry[e].attr,c=[];if("gl2d"===e){var u=r.match(a);o="x"+u[1],l="y"+u[2]}for(var f=0;f<t.length;f++)i=t[f],"gl2d"===e&&n.traceIs(i,"gl2d")?i[s[0]]===o&&i[s[1]]===l&&c.push(i):i[s]===r&&c.push(i);return c},r.getUidsFromCalcData=function(t){for(var e={},r=0;r<t.length;r++){e[t[r][0].trace.uid]=1}return e}},{"../registry":247,"./cartesian/constants":212}],236:[function(t,e,r){"use strict";function n(t,e){var r,n,a=[0,0,0,0];for(r=0;r<4;++r)for(n=0;n<4;++n)a[n]+=t[4*r+n]*e[r];return a}e.exports=function(t,e){return n(t.projection,n(t.view,n(t.model,[e[0],e[1],e[2],1])))}},{}],237:[function(t,e,r){"use strict";var n=t("./font_attributes"),a=t("../components/color/attributes"),i=n({editType:"calc"});i.family.dflt='"Open Sans", verdana, arial, sans-serif',i.size.dflt=12,i.color.dflt=a.defaultLine,e.exports={font:i,title:{valType:"string",editType:"layoutstyle"},titlefont:n({editType:"layoutstyle"}),autosize:{valType:"boolean",dflt:!1,editType:"none"},width:{valType:"number",min:10,dflt:700,editType:"plot"},height:{valType:"number",min:10,dflt:450,editType:"plot"},margin:{l:{valType:"number",min:0,dflt:80,editType:"plot"},r:{valType:"number",min:0,dflt:80,editType:"plot"},t:{valType:"number",min:0,dflt:100,editType:"plot"},b:{valType:"number",min:0,dflt:80,editType:"plot"},pad:{valType:"number",min:0,dflt:0,editType:"plot"},autoexpand:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},paper_bgcolor:{valType:"color",dflt:a.background,editType:"plot"},plot_bgcolor:{valType:"color",dflt:a.background,editType:"layoutstyle"},separators:{valType:"string",editType:"plot"},hidesources:{valType:"boolean",dflt:!1,editType:"plot"},showlegend:{valType:"boolean",editType:"legend"},colorway:{valType:"colorlist",dflt:a.defaults,editType:"calc"},datarevision:{valType:"any",editType:"calc"},template:{valType:"any",editType:"calc"}}},{"../components/color/attributes":44,"./font_attributes":233}],238:[function(t,e,r){"use strict";e.exports={t:{valType:"number",dflt:0,editType:"arraydraw"},r:{valType:"number",dflt:0,editType:"arraydraw"},b:{valType:"number",dflt:0,editType:"arraydraw"},l:{valType:"number",dflt:0,editType:"arraydraw"},editType:"arraydraw"}},{}],239:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("../registry"),o=t("../plot_api/plot_schema"),l=t("../plot_api/plot_template"),s=t("../lib"),c=t("../components/color"),u=t("../constants/numerical").BADNUM,f=t("../plots/cartesian/axis_ids"),d=t("./sort_modules").sortBasePlotModules,p=t("./animation_attributes"),h=t("./frame_attributes"),g=s.relinkPrivateKeys,y=s._,v=e.exports={};s.extendFlat(v,i),v.attributes=t("./attributes"),v.attributes.type.values=v.allTypes,v.fontAttrs=t("./font_attributes"),v.layoutAttributes=t("./layout_attributes"),v.fontWeight="normal";var m=v.transformsRegistry,x=t("./command");v.executeAPICommand=x.executeAPICommand,v.computeAPICommandBindings=x.computeAPICommandBindings,v.manageCommandObserver=x.manageCommandObserver,v.hasSimpleAPICommandBindings=x.hasSimpleAPICommandBindings,v.redrawText=function(t){if(!((t=s.getGraphDiv(t)).data&&t.data[0]&&t.data[0].r))return new Promise(function(e){setTimeout(function(){i.getComponentMethod("annotations","draw")(t),i.getComponentMethod("legend","draw")(t),(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()}),e(v.previousPromises(t))},300)})},v.resize=function(t){return t=s.getGraphDiv(t),new Promise(function(e,r){function n(t){var e=window.getComputedStyle(t).display;return!e||"none"===e}t&&!n(t)||r(new Error("Resize must be passed a displayed plot div element.")),t._redrawTimer&&clearTimeout(t._redrawTimer),t._redrawTimer=setTimeout(function(){if(!t.layout||t.layout.width&&t.layout.height||n(t))e(t);else{delete t.layout.width,delete t.layout.height;var r=t.changed;t.autoplay=!0,i.call("relayout",t,{autosize:!0}).then(function(){t.changed=r,e(t)})}},100)})},v.previousPromises=function(t){if((t._promises||[]).length)return Promise.all(t._promises).then(function(){t._promises=[]})},v.addLinks=function(t){if(t._context.showLink||t._context.showSources){var e=t._fullLayout,r=s.ensureSingle(e._paper,"text","js-plot-link-container",function(t){t.style({"font-family":'"Open Sans", Arial, sans-serif',"font-size":"12px",fill:c.defaultLine,"pointer-events":"all"}).each(function(){var t=n.select(this);t.append("tspan").classed("js-link-to-tool",!0),t.append("tspan").classed("js-link-spacer",!0),t.append("tspan").classed("js-sourcelinks",!0)})}),a=r.node(),i={y:e._paper.attr("height")-9};document.body.contains(a)&&a.getComputedTextLength()>=e.width-20?(i["text-anchor"]="start",i.x=5):(i["text-anchor"]="end",i.x=e._paper.attr("width")-7),r.attr(i);var o=r.select(".js-link-to-tool"),l=r.select(".js-link-spacer"),u=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&function(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#",class:"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){v.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),a=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+a})}}(t,o),l.text(o.text()&&u.text()?" - ":"")}},v.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=(window.PLOTLYENV||{}).BASE_URL||t._context.plotlyServerURL,r=n.select(t).append("div").attr("id","hiddenform").style("display","none"),a=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"});return a.append("input").attr({type:"text",name:"data"}).node().value=v.graphJson(t,!1,"keepdata"),a.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1};var b,_=["days","shortDays","months","shortMonths","periods","dateTime","date","time","decimal","thousands","grouping","currency"],w=["year","month","dayMonth","dayMonthYear"];function k(t,e){var r=t._context.locale,n=!1,a={};function o(t){for(var r=!0,i=0;i<e.length;i++){var o=e[i];a[o]||(t[o]?a[o]=t[o]:r=!1)}r&&(n=!0)}for(var l=0;l<2;l++){for(var s=t._context.locales,c=0;c<2;c++){var u=(s[r]||{}).format;if(u&&(o(u),n))break;s=i.localeRegistry}var f=r.split("-")[0];if(n||f===r)break;r=f}return n||o(i.localeRegistry.en.format),a}function M(t,e,r,n){for(var a=t.transforms,i=[t],o=0;o<a.length;o++){var l=a[o],s=m[l.type];s&&s.transform&&(i=s.transform(i,{transform:l,fullTrace:t,fullData:e,layout:r,fullLayout:n,transformIndex:o}))}return i}function T(t){t._pushmargin||(t._pushmargin={}),t._pushmarginIds||(t._pushmarginIds={})}function A(t){for(var e=0;e<t.length;e++)t[e].clearCalc()}v.supplyDefaults=function(t,e){var r=e&&e.skipUpdateCalc,a=t._fullLayout||{};if(a._skipDefaults)delete a._skipDefaults;else{var o,l=t._fullLayout={},c=t.layout||{},u=t._fullData||[],p=t._fullData=[],h=t.data||[],m=t.calcdata||[],x=t._context||{};t._transitionData||v.createTransitionData(t),l._dfltTitle={plot:y(t,"Click to enter Plot title"),x:y(t,"Click to enter X axis title"),y:y(t,"Click to enter Y axis title"),colorbar:y(t,"Click to enter Colorscale title"),annotation:y(t,"new text")},l._traceWord=y(t,"trace");var M=k(t,_);if(l._mapboxAccessToken=x.mapboxAccessToken,a._initialAutoSizeIsDone){var T=a.width,A=a.height;v.supplyLayoutGlobalDefaults(c,l,M),c.width||(l.width=T),c.height||(l.height=A),v.sanitizeMargins(l)}else{v.supplyLayoutGlobalDefaults(c,l,M);var L=!c.width||!c.height,C=l.autosize,S=x.autosizable;L&&(C||S)?v.plotAutoSize(t,c,l):L&&v.sanitizeMargins(l),!C&&L&&(c.width=l.width,c.height=l.height)}l._d3locale=function(t,e){return t.decimal=e.charAt(0),t.thousands=e.charAt(1),n.locale(t)}(M,l.separators),l._extraFormat=k(t,w),l._initialAutoSizeIsDone=!0,l._dataLength=h.length,l._modules=[],l._basePlotModules=[];var O=l._subplots=function(){var t,e,r={};if(!b){b=[];var n=i.subplotsRegistry;for(var a in n){var o=n[a],l=o.attr;if(l&&(b.push(a),Array.isArray(l)))for(e=0;e<l.length;e++)s.pushUnique(b,l[e])}}for(t=0;t<b.length;t++)r[b[t]]=[];return r}(),P=l._splomAxes={x:{},y:{}},D=l._splomSubplots={};l._splomGridDflt={},l._requestRangeslider={},l._traceUids=function(t,e){var r,n,a=e.length,i=[];for(r=0;r<t.length;r++){var o=t[r]._fullInput;o!==n&&i.push(o),n=o}var l=i.length,c=new Array(a),u={};function f(t,e){c[e]=t,u[t]=1}function d(t,e){if(t&&"string"==typeof t&&!u[t])return f(t,e),!0}for(r=0;r<a;r++)d(e[r].uid,r)||r<l&&d(i[r].uid,r)||f(s.randstr(u),r);return c}(u,h),l._globalTransforms=(t._context||{}).globalTransforms,v.supplyDataDefaults(h,p,c,l);var z=Object.keys(P.x),E=Object.keys(P.y);if(z.length>1&&E.length>1){for(i.getComponentMethod("grid","sizeDefaults")(c,l),o=0;o<z.length;o++)s.pushUnique(O.xaxis,z[o]);for(o=0;o<E.length;o++)s.pushUnique(O.yaxis,E[o]);for(var I in D)s.pushUnique(O.cartesian,I)}l._has=v._hasPlotType.bind(l);var N=l._modules;for(o=0;o<N.length;o++){var R=N[o];R.cleanData&&R.cleanData(p)}if(u.length===p.length)for(o=0;o<p.length;o++)g(p[o],u[o]);v.supplyLayoutModuleDefaults(c,l,p,t._transitionData),l._hasOnlyLargeSploms=1===l._basePlotModules.length&&"splom"===l._basePlotModules[0].name&&z.length>15&&E.length>15&&0===l.shapes.length&&0===l.images.length,l._hasCartesian=l._has("cartesian"),l._hasGeo=l._has("geo"),l._hasGL3D=l._has("gl3d"),l._hasGL2D=l._has("gl2d"),l._hasTernary=l._has("ternary"),l._hasPie=l._has("pie"),v.linkSubplots(p,l,u,a),v.cleanPlot(p,l,u,a,m),g(l,a),v.doAutoMargin(t);var F=f.list(t);for(o=0;o<F.length;o++){F[o].setScale()}r||m.length!==p.length||v.supplyDefaultsUpdateCalc(m,p),l._basePlotModules.sort(d)}},v.supplyDefaultsUpdateCalc=function(t,e){for(var r=0;r<e.length;r++){var n=e[r],a=t[r][0];if(a&&a.trace){var i=a.trace;if(i._hasCalcTransform){var o,l,c,u=i._arrayAttrs;for(o=0;o<u.length;o++)l=u[o],c=s.nestedProperty(i,l).get().slice(),s.nestedProperty(n,l).set(c)}a.trace=n}}},v.createTransitionData=function(t){t._transitionData||(t._transitionData={}),t._transitionData._frames||(t._transitionData._frames=[]),t._transitionData._frameHash||(t._transitionData._frameHash={}),t._transitionData._counter||(t._transitionData._counter=0),t._transitionData._interruptCallbacks||(t._transitionData._interruptCallbacks=[])},v._hasPlotType=function(t){var e,r=this._basePlotModules||[];for(e=0;e<r.length;e++)if(r[e].name===t)return!0;var n=this._modules||[];for(e=0;e<n.length;e++){var a=n[e].name;if(a===t)return!0;var o=i.modules[a];if(o&&o.categories[t])return!0}return!1},v.cleanPlot=function(t,e,r,n,a){var i,o,l=n._basePlotModules||[];for(i=0;i<l.length;i++){var s=l[i];s.clean&&s.clean(t,e,r,n,a)}var c=n._has&&n._has("gl"),u=e._has&&e._has("gl");c&&!u&&void 0!==n._glcontainer&&(n._glcontainer.selectAll(".gl-canvas").remove(),n._glcontainer.selectAll(".no-webgl").remove(),n._glcanvas=null);var f=!!n._infolayer;t:for(i=0;i<r.length;i++){var d=r[i].uid;for(o=0;o<t.length;o++){if(d===t[o].uid)continue t}f&&n._infolayer.select(".cb"+d).remove()}n._zoomlayer&&n._zoomlayer.selectAll(".select-outline").remove()},v.linkSubplots=function(t,e,r,n){var a,i,o,l,s=n._plots||{},c=e._plots={},u=e._subplots,d={_fullData:t,_fullLayout:e},p=u.cartesian.concat(u.gl2d||[]);for(a=0;a<p.length;a++){var h,g=s[o=p[a]],y=f.getFromId(d,o,"x"),v=f.getFromId(d,o,"y");for(g?((h=c[o]=g).xaxis.layer!==y.layer&&(h.xlines.attr("d",null),h.xaxislayer.selectAll("*").remove()),h.yaxis.layer!==v.layer&&(h.ylines.attr("d",null),h.yaxislayer.selectAll("*").remove())):(h=c[o]={}).id=o,h.xaxis=y,h.yaxis=v,h._hasClipOnAxisFalse=!1,i=0;i<t.length;i++){var m=t[i];if(m.xaxis===h.xaxis._id&&m.yaxis===h.yaxis._id&&!1===m.cliponaxis){h._hasClipOnAxisFalse=!0;break}}}var x=f.list(d,null,!0);for(a=0;a<x.length;a++){var b=null;(l=x[a]).overlaying&&(b=f.getFromId(d,l.overlaying))&&b.overlaying&&(l.overlaying=!1,b=null),l._mainAxis=b||l,b&&(l.domain=b.domain.slice()),l._anchorAxis="free"===l.anchor?null:f.getFromId(d,l.anchor)}},v.clearExpandedTraceDefaultColors=function(t){var e,r,n;for(r=[],(e=t._module._colorAttrs)||(t._module._colorAttrs=e=[],o.crawl(t._module.attributes,function(t,n,a,i){r[i]=n,r.length=i+1,"color"===t.valType&&void 0===t.dflt&&e.push(r.join("."))})),n=0;n<e.length;n++){s.nestedProperty(t,"_input."+e[n]).get()||s.nestedProperty(t,e[n]).set(null)}},v.supplyDataDefaults=function(t,e,r,n){var a,o,c,u=n._modules,f=n._basePlotModules,d=0,p=0;function h(t){e.push(t);var r=t._module;r&&(!0===t.visible&&s.pushUnique(u,r),s.pushUnique(f,t._module.basePlotModule),d++,!1!==t._input.visible&&p++)}n._transformModules=[];var y={},m=[],x=(r.template||{}).data||{},b=l.traceTemplater(x);for(a=0;a<t.length;a++){if(c=t[a],(o=b.newTrace(c)).uid=n._traceUids[a],v.supplyTraceDefaults(c,o,p,n,a),o.uid=n._traceUids[a],o.index=a,o._input=c,o._expandedIndex=d,o.transforms&&o.transforms.length)for(var _=M(o,e,r,n),w=0;w<_.length;w++){var k=_[w],T={_template:o._template,type:o.type,uid:o.uid+w};v.supplyTraceDefaults(k,T,d,n,a),g(T,k),T.index=a,T._input=c,T._fullInput=o,T._expandedIndex=d,T._expandedInput=k,h(T)}else o._fullInput=o,o._expandedInput=o,h(o);i.traceIs(o,"carpetAxis")&&(y[o.carpet]=o),i.traceIs(o,"carpetDependent")&&m.push(a)}for(a=0;a<m.length;a++)if((o=e[m[a]]).visible){var A=y[o.carpet];o._carpet=A,A&&A.visible?(o.xaxis=A.xaxis,o.yaxis=A.yaxis):o.visible=!1}},v.supplyAnimationDefaults=function(t){var e;t=t||{};var r={};function n(e,n){return s.coerce(t||{},r,p,e,n)}if(n("mode"),n("direction"),n("fromcurrent"),Array.isArray(t.frame))for(r.frame=[],e=0;e<t.frame.length;e++)r.frame[e]=v.supplyAnimationFrameDefaults(t.frame[e]||{});else r.frame=v.supplyAnimationFrameDefaults(t.frame||{});if(Array.isArray(t.transition))for(r.transition=[],e=0;e<t.transition.length;e++)r.transition[e]=v.supplyAnimationTransitionDefaults(t.transition[e]||{});else r.transition=v.supplyAnimationTransitionDefaults(t.transition||{});return r},v.supplyAnimationFrameDefaults=function(t){var e={};function r(r,n){return s.coerce(t||{},e,p.frame,r,n)}return r("duration"),r("redraw"),e},v.supplyAnimationTransitionDefaults=function(t){var e={};function r(r,n){return s.coerce(t||{},e,p.transition,r,n)}return r("duration"),r("easing"),e},v.supplyFrameDefaults=function(t){var e={};function r(r,n){return s.coerce(t,e,h,r,n)}return r("group"),r("name"),r("traces"),r("baseframe"),r("data"),r("layout"),e},v.supplyTraceDefaults=function(t,e,r,n,a){var o,l=n.colorway||c.defaults,u=l[r%l.length];function f(r,n){return s.coerce(t,e,v.attributes,r,n)}var d=f("visible");f("type"),f("name",n._traceWord+" "+a);var p=v.getModule(e);if(e._module=p,p){var h=p.basePlotModule,g=h.attr,y=h.attributes;if(g&&y){var m=n._subplots,x="";if("gl2d"!==h.name||d){if(Array.isArray(g))for(o=0;o<g.length;o++){var b=g[o],_=s.coerce(t,e,y,b);m[b]&&s.pushUnique(m[b],_),x+=_}else x=s.coerce(t,e,y,g);m[h.name]&&s.pushUnique(m[h.name],x)}}}return d&&(f("customdata"),f("ids"),i.traceIs(e,"showLegend")&&(f("showlegend"),f("legendgroup")),i.getComponentMethod("fx","supplyDefaults")(t,e,u,n),p&&(p.supplyDefaults(t,e,u,n),s.coerceHoverinfo(t,e,n)),i.traceIs(e,"noOpacity")||f("opacity"),i.traceIs(e,"notLegendIsolatable")&&(e.visible=!!e.visible),p&&p.selectPoints&&f("selectedpoints"),v.supplyTransformDefaults(t,e,n)),e},v.supplyTransformDefaults=function(t,e,r){if(e._length||function(t){var e=t.transforms;if(Array.isArray(e)&&e.length)for(var r=0;r<e.length;r++){var n=m[e[r].type];if(n&&n.makesData)return!0}return!1}(t)){var n=r._globalTransforms||[],a=r._transformModules||[];if(Array.isArray(t.transforms)||0!==n.length)for(var i=t.transforms||[],o=n.concat(i),l=e.transforms=[],c=0;c<o.length;c++){var u,f=o[c],d=f.type,p=m[d],h=!(f._module&&f._module===p),g=p&&"function"==typeof p.transform;p||s.warn("Unrecognized transform type "+d+"."),p&&p.supplyDefaults&&(h||g)?((u=p.supplyDefaults(f,e,r,t)).type=d,u._module=p,s.pushUnique(a,p)):u=s.extendFlat({},f),l.push(u)}}},v.supplyLayoutGlobalDefaults=function(t,e,r){function n(r,n){return s.coerce(t,e,v.layoutAttributes,r,n)}var a=t.template;s.isPlainObject(a)&&(e.template=a,e._template=a.layout,e._dataTemplate=a.data);var o=s.coerceFont(n,"font");n("title",e._dfltTitle.plot),s.coerceFont(n,"titlefont",{family:o.family,size:Math.round(1.4*o.size),color:o.color}),n("autosize",!(t.width&&t.height)),n("width"),n("height"),n("margin.l"),n("margin.r"),n("margin.t"),n("margin.b"),n("margin.pad"),n("margin.autoexpand"),t.width&&t.height&&v.sanitizeMargins(e),i.getComponentMethod("grid","sizeDefaults")(t,e),n("paper_bgcolor"),n("separators",r.decimal+r.thousands),n("hidesources"),n("colorway"),n("datarevision"),i.getComponentMethod("calendars","handleDefaults")(t,e,"calendar"),i.getComponentMethod("fx","supplyLayoutGlobalDefaults")(t,e,n)},v.plotAutoSize=function(t,e,r){var n,i,o=t._context||{},l=o.frameMargins,c=s.isPlotDiv(t);if(c&&t.emit("plotly_autosize"),o.fillFrame)n=window.innerWidth,i=window.innerHeight,document.body.style.overflow="hidden";else if(a(l)&&l>0){var u=function(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}(t._boundingBoxMargins),f=u.left+u.right,d=u.bottom+u.top,p=1-2*l,h=r._container&&r._container.node?r._container.node().getBoundingClientRect():{width:r.width,height:r.height};n=Math.round(p*(h.width-f)),i=Math.round(p*(h.height-d))}else{var g=c?window.getComputedStyle(t):{};n=parseFloat(g.width)||r.width,i=parseFloat(g.height)||r.height}var y=v.layoutAttributes.width.min,m=v.layoutAttributes.height.min;n<y&&(n=y),i<m&&(i=m);var x=!e.width&&Math.abs(r.width-n)>1,b=!e.height&&Math.abs(r.height-i)>1;(b||x)&&(x&&(r.width=n),b&&(r.height=i)),t._initialAutoSize||(t._initialAutoSize={width:n,height:i}),v.sanitizeMargins(r)},v.supplyLayoutModuleDefaults=function(t,e,r,n){var a,o,l,c=i.componentsRegistry,u=e._basePlotModules,f=i.subplotsRegistry.cartesian;for(a in c)(l=c[a]).includeBasePlot&&l.includeBasePlot(t,e);for(var d in u.length||u.push(f),e._has("cartesian")&&(i.getComponentMethod("grid","contentDefaults")(t,e),f.finalizeSubplots(t,e)),e._subplots)e._subplots[d].sort(s.subplotSort);for(o=0;o<u.length;o++)(l=u[o]).supplyLayoutDefaults&&l.supplyLayoutDefaults(t,e,r);var p=e._modules;for(o=0;o<p.length;o++)(l=p[o]).supplyLayoutDefaults&&l.supplyLayoutDefaults(t,e,r);var h=e._transformModules;for(o=0;o<h.length;o++)(l=h[o]).supplyLayoutDefaults&&l.supplyLayoutDefaults(t,e,r,n);for(a in c)(l=c[a]).supplyLayoutDefaults&&l.supplyLayoutDefaults(t,e,r)},v.purge=function(t){var e=t._fullLayout||{};void 0!==e._glcontainer&&(e._glcontainer.selectAll(".gl-canvas").remove(),e._glcontainer.remove(),e._glcanvas=null),void 0!==e._geocontainer&&e._geocontainer.remove(),e._modeBar&&e._modeBar.destroy(),t._transitionData&&(t._transitionData._interruptCallbacks&&(t._transitionData._interruptCallbacks.length=0),t._transitionData._animationRaf&&window.cancelAnimationFrame(t._transitionData._animationRaf)),s.clearThrottle(),delete t.data,delete t.layout,delete t._fullData,delete t._fullLayout,delete t.calcdata,delete t.framework,delete t.empty,delete t.fid,delete t.undoqueue,delete t.undonum,delete t.autoplay,delete t.changed,delete t._promises,delete t._redrawTimer,delete t.firstscatter,delete t._hmlumcount,delete t._hmpixcount,delete t._transitionData,delete t._transitioning,delete t._initialAutoSize,delete t._transitioningWithDuration,delete t._dragging,delete t._dragged,delete t._hoverdata,delete t._snapshotInProgress,delete t._editing,delete t._replotPending,delete t._mouseDownTime,delete t._legendMouseDownTime,t.removeAllListeners&&t.removeAllListeners()},v.style=function(t){var e,r=t._fullLayout._modules,n=[];for(e=0;e<r.length;e++){var a=r[e];a.style&&s.pushUnique(n,a.style)}for(e=0;e<n.length;e++)n[e](t)},v.sanitizeMargins=function(t){if(t&&t.margin){var e,r=t.width,n=t.height,a=t.margin,i=r-(a.l+a.r),o=n-(a.t+a.b);i<0&&(e=(r-1)/(a.l+a.r),a.l=Math.floor(e*a.l),a.r=Math.floor(e*a.r)),o<0&&(e=(n-1)/(a.t+a.b),a.t=Math.floor(e*a.t),a.b=Math.floor(e*a.b))}},v.clearAutoMarginIds=function(t){t._fullLayout._pushmarginIds={}},v.allowAutoMargin=function(t,e){t._fullLayout._pushmarginIds[e]=1},v.autoMargin=function(t,e,r){var n=t._fullLayout;T(n);var a=n._pushmargin,i=n._pushmarginIds;if(!1!==n.margin.autoexpand){if(r){var o=r.pad;if(void 0===o){var l=n.margin;o=Math.min(12,l.l,l.r,l.t,l.b)}r.l+r.r>.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0);var s=void 0!==r.xl?r.xl:r.x,c=void 0!==r.xr?r.xr:r.x,u=void 0!==r.yt?r.yt:r.y,f=void 0!==r.yb?r.yb:r.y;a[e]={l:{val:s,size:r.l+o},r:{val:c,size:r.r+o},b:{val:f,size:r.b+o},t:{val:u,size:r.t+o}},i[e]=1}else delete a[e],delete i[e];n._replotting||v.doAutoMargin(t)}},v.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),T(e);var r=e._size,n=JSON.stringify(r),o=Math.max(e.margin.l||0,0),l=Math.max(e.margin.r||0,0),s=Math.max(e.margin.t||0,0),c=Math.max(e.margin.b||0,0),u=e._pushmargin,f=e._pushmarginIds;if(!1!==e.margin.autoexpand){for(var d in u)f[d]||delete u[d];for(var p in u.base={l:{val:0,size:o},r:{val:1,size:l},t:{val:1,size:s},b:{val:0,size:c}},u){var h=u[p].l||{},g=u[p].b||{},y=h.val,v=h.size,m=g.val,x=g.size;for(var b in u){if(a(v)&&u[b].r){var _=u[b].r.val,w=u[b].r.size;if(_>y){var k=(v*_+(w-e.width)*y)/(_-y),M=(w*(1-y)+(v-e.width)*(1-_))/(_-y);k>=0&&M>=0&&k+M>o+l&&(o=k,l=M)}}if(a(x)&&u[b].t){var A=u[b].t.val,L=u[b].t.size;if(A>m){var C=(x*A+(L-e.height)*m)/(A-m),S=(L*(1-m)+(x-e.height)*(1-A))/(A-m);C>=0&&S>=0&&C+S>c+s&&(c=C,s=S)}}}}}if(r.l=Math.round(o),r.r=Math.round(l),r.t=Math.round(s),r.b=Math.round(c),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,!e._replotting&&"{}"!==n&&n!==JSON.stringify(e._size))return"_redrawFromAutoMarginCount"in e?e._redrawFromAutoMarginCount++:e._redrawFromAutoMarginCount=1,i.call("plot",t)},v.graphJson=function(t,e,r,n,a){(a&&e&&!t._fullData||a&&!e&&!t._fullLayout)&&v.supplyDefaults(t);var i=a?t._fullData:t.data,o=a?t._fullLayout:t.layout,l=(t._transitionData||{})._frames;function c(t){if("function"==typeof t)return null;if(s.isPlainObject(t)){var e,n,a={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if("string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0&&!s.isPlainObject(t.stream))continue}else if("keepall"!==r&&"string"==typeof(n=t[e+"src"])&&n.indexOf(":")>0)continue;a[e]=c(t[e])}return a}return Array.isArray(t)?t.map(c):s.isJSDate(t)?s.ms2DateTimeLocal(+t):t}var u={data:(i||[]).map(function(t){var r=c(t);return e&&delete r.fit,r})};return e||(u.layout=c(o)),t.framework&&t.framework.isPolar&&(u=t.framework.getConfig()),l&&(u.frames=c(l)),"object"===n?u:JSON.stringify(u)},v.modifyFrames=function(t,e){var r,n,a,i=t._transitionData._frames,o=t._transitionData._frameHash;for(r=0;r<e.length;r++)switch((n=e[r]).type){case"replace":a=n.value;var l=(i[n.index]||{}).name,s=a.name;i[n.index]=o[s]=a,s!==l&&(delete o[l],o[s]=a);break;case"insert":o[(a=n.value).name]=a,i.splice(n.index,0,a);break;case"delete":delete o[(a=i[n.index]).name],i.splice(n.index,1)}return Promise.resolve()},v.computeFrame=function(t,e){var r,n,a,i,o=t._transitionData._frameHash;if(!e)throw new Error("computeFrame must be given a string frame name");var l=o[e.toString()];if(!l)return!1;for(var s=[l],c=[l.name];l.baseframe&&(l=o[l.baseframe.toString()])&&-1===c.indexOf(l.name);)s.push(l),c.push(l.name);for(var u={};l=s.pop();)if(l.layout&&(u.layout=v.extendLayout(u.layout,l.layout)),l.data){if(u.data||(u.data=[]),!(n=l.traces))for(n=[],r=0;r<l.data.length;r++)n[r]=r;for(u.traces||(u.traces=[]),r=0;r<l.data.length;r++)null!=(a=n[r])&&(-1===(i=u.traces.indexOf(a))&&(i=u.data.length,u.traces[i]=a),u.data[i]=v.extendTrace(u.data[i],l.data[r]))}return u},v.recomputeFrameHash=function(t){for(var e=t._transitionData._frameHash={},r=t._transitionData._frames,n=0;n<r.length;n++){var a=r[n];a&&a.name&&(e[a.name]=a)}},v.extendObjectWithContainers=function(t,e,r){var n,a,i,o,l,c,u,f=s.extendDeepNoArrays({},e||{}),d=s.expandObjectPaths(f),p={};if(r&&r.length)for(i=0;i<r.length;i++)void 0===(a=(n=s.nestedProperty(d,r[i])).get())?s.nestedProperty(p,r[i]).set(null):(n.set(null),s.nestedProperty(p,r[i]).set(a));if(t=s.extendDeepNoArrays(t||{},d),r&&r.length)for(i=0;i<r.length;i++)if(c=s.nestedProperty(p,r[i]).get()){for(u=(l=s.nestedProperty(t,r[i])).get(),Array.isArray(u)||(u=[],l.set(u)),o=0;o<c.length;o++){var h=c[o];u[o]=null===h?null:v.extendObjectWithContainers(u[o],h)}l.set(u)}return t},v.dataArrayContainers=["transforms","dimensions"],v.layoutArrayContainers=i.layoutArrayContainers,v.extendTrace=function(t,e){return v.extendObjectWithContainers(t,e,v.dataArrayContainers)},v.extendLayout=function(t,e){return v.extendObjectWithContainers(t,e,v.layoutArrayContainers)},v.transition=function(t,e,r,n,a,o){var l,c,u=Array.isArray(e)?e.length:0,f=n.slice(0,u),d=[];var p=!1;for(l=0;l<f.length;l++){c=f[l];t._fullData[c]._module}var h=[v.previousPromises,function(){if(t._transitionData)return t._transitioning=!1,function(t){var e=Promise.resolve();if(!t)return e;for(;t.length;)e=e.then(t.shift());return e}(t._transitionData._interruptCallbacks)},function(){var n;for(n=0;n<f.length;n++){var a=f[n],o=t._fullData[a]._module;o&&(o.animatable&&d.push(a),t.data[f[n]]=v.extendTrace(t.data[f[n]],e[n]))}var l=s.expandObjectPaths(s.extendDeepNoArrays({},r)),c=/^[xy]axis[0-9]*$/;for(var u in l)c.test(u)&&delete l[u].range;return v.extendLayout(t.layout,l),delete t.calcdata,v.supplyDefaults(t),v.doCalcdata(t),v.doSetPositions(t),i.getComponentMethod("errorbars","calc")(t),Promise.resolve()},v.rehover,function(){return t.emit("plotly_transitioning",[]),new Promise(function(e){t._transitioning=!0,o.duration>0&&(t._transitioningWithDuration=!0),t._transitionData._interruptCallbacks.push(function(){p=!0}),a.redraw&&t._transitionData._interruptCallbacks.push(function(){return i.call("redraw",t)}),t._transitionData._interruptCallbacks.push(function(){t.emit("plotly_transitioninterrupted",[])});var n,l,c=0,u=0;function f(){return c++,function(){var r;u++,p||u!==c||(r=e,t._transitionData&&(function(t){if(t)for(;t.length;)t.shift()}(t._transitionData._interruptCallbacks),Promise.resolve().then(function(){if(a.redraw)return i.call("redraw",t)}).then(function(){t._transitioning=!1,t._transitioningWithDuration=!1,t.emit("plotly_transitioned",[])}).then(r)))}}var h=t._fullLayout._basePlotModules,g=!1;if(r)for(l=0;l<h.length;l++)if(h[l].transitionAxes){var y=s.expandObjectPaths(r);g=h[l].transitionAxes(t,y,o,f)||g}for(g?((n=s.extendFlat({},o)).duration=0,d=null):n=o,l=0;l<h.length;l++)h[l].plot(t,d,n,f);setTimeout(f())})}],g=s.syncOrAsync(h,t);return g&&g.then||(g=Promise.resolve()),g.then(function(){return t})},v.doCalcdata=function(t,e){var r,n,a,l,s=f.list(t),c=t._fullData,d=t._fullLayout,p=new Array(c.length),h=(t.calcdata||[]).slice(0);for(t.calcdata=p,t.firstscatter=!0,d._numBoxes=0,d._numViolins=0,d._violinScaleGroupStats={},t._hmpixcount=0,t._hmlumcount=0,d._piecolormap={},d._piecolorway=null,d._piedefaultcolorcount=0,a=0;a<c.length;a++)Array.isArray(e)&&-1===e.indexOf(a)&&(p[a]=h[a]);for(a=0;a<c.length;a++)(r=c[a])._arrayAttrs=o.findArrayAttributes(r);var g=d._subplots.polar||[];for(a=0;a<g.length;a++)s.push(d[g[a]].radialaxis,d[g[a]].angularaxis);A(s);var y=!1;for(a=0;a<c.length;a++)if(!0===(r=c[a]).visible&&r.transforms){if((n=r._module)&&n.calc){var v=n.calc(t,r);v[0]&&v[0].t&&v[0].t._scene&&delete v[0].t._scene.dirty}for(l=0;l<r.transforms.length;l++){var x=r.transforms[l];(n=m[x.type])&&n.calcTransform&&(r._hasCalcTransform=!0,y=!0,n.calcTransform(t,r,x))}}function b(e,a){if(r=c[e],!!(n=r._module).isContainer===a){var i=[];if(!0===r.visible){delete r._indexToPoints;var o=r.transforms||[];for(l=o.length-1;l>=0;l--)if(o[l].enabled){r._indexToPoints=o[l]._indexToPoints;break}n&&n.calc&&(i=n.calc(t,r))}Array.isArray(i)&&i[0]||(i=[{x:u,y:u}]),i[0].t||(i[0].t={}),i[0].trace=r,p[e]=i}}for(y&&A(s),a=0;a<c.length;a++)b(a,!0);for(a=0;a<c.length;a++)b(a,!1);i.getComponentMethod("fx","calc")(t)},v.doSetPositions=function(t){var e,r,n=t._fullLayout,a=n._subplots.cartesian,i=n._modules,o=[];for(r=0;r<i.length;r++)s.pushUnique(o,i[r].setPositions);if(o.length)for(e=0;e<a.length;e++){var l=n._plots[a[e]];for(r=0;r<o.length;r++)o[r](t,l)}},v.rehover=function(t){t._fullLayout._rehover&&t._fullLayout._rehover()},v.generalUpdatePerTraceModule=function(t,e,r,n){var a,i=e.traceHash,o={};for(a=0;a<r.length;a++){var l=r[a],c=l[0].trace;c.visible&&(o[c.type]=o[c.type]||[],o[c.type].push(l))}for(var u in i)if(!o[u]){var f=i[u][0];f[0].trace.visible=!1,o[u]=[f]}for(var d in o){var p=o[d];p[0][0].trace._module.plot(t,e,s.filterVisible(p),n)}e.traceHash=o}},{"../components/color":45,"../constants/numerical":145,"../lib":163,"../plot_api/plot_schema":196,"../plot_api/plot_template":197,"../plots/cartesian/axis_ids":210,"../registry":247,"./animation_attributes":202,"./attributes":204,"./command":231,"./font_attributes":233,"./frame_attributes":234,"./layout_attributes":237,"./sort_modules":246,d3:10,"fast-isnumeric":13}],240:[function(t,e,r){"use strict";var n=t("../../../traces/scatter/attributes"),a=n.marker;e.exports={r:n.r,t:n.t,marker:{color:a.color,size:a.size,symbol:a.symbol,opacity:a.opacity,editType:"calc"}}},{"../../../traces/scatter/attributes":314}],241:[function(t,e,r){"use strict";var n=t("../../cartesian/layout_attributes"),a=t("../../../lib/extend").extendFlat,i=t("../../../plot_api/edit_types").overrideAll,o=a({},n.domain,{});function l(t,e){return a({},e,{showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}})}e.exports=i({radialaxis:l(0,{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:o,orientation:{valType:"number"}}),angularaxis:l(0,{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:o}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}},"plot","nested")},{"../../../lib/extend":157,"../../../plot_api/edit_types":190,"../../cartesian/layout_attributes":219}],242:[function(t,e,r){"use strict";(e.exports=t("./micropolar")).manager=t("./micropolar_manager")},{"./micropolar":243,"./micropolar_manager":244}],243:[function(t,e,r){var n=t("d3"),a=t("../../../lib").extendDeepAll,i=t("../../../constants/alignment").MID_SHIFT,o=e.exports={version:"0.2.2"};o.Axis=function(){var t,e,r,l,s={data:[],layout:{}},c={},u={},f=n.dispatch("hover"),d={};return d.render=function(c){return function(c){e=c||e;var f=s.data,d=s.layout;("string"==typeof e||e.nodeName)&&(e=n.select(e)),e.datum(f).each(function(e,s){var c=e.slice();u={data:o.util.cloneJson(c),layout:o.util.cloneJson(d)};var f=0;c.forEach(function(t,e){t.color||(t.color=d.defaultColorRange[f],f=(f+1)%d.defaultColorRange.length),t.strokeColor||(t.strokeColor="LinePlot"===t.geometry?t.color:n.rgb(t.color).darker().toString()),u.data[e].color=t.color,u.data[e].strokeColor=t.strokeColor,u.data[e].strokeDash=t.strokeDash,u.data[e].strokeSize=t.strokeSize});var p=c.filter(function(t,e){var r=t.visible;return"undefined"==typeof r||!0===r}),h=!1,g=p.map(function(t,e){return h=h||"undefined"!=typeof t.groupId,t});if(h){var y=n.nest().key(function(t,e){return"undefined"!=typeof t.groupId?t.groupId:"unstacked"}).entries(g),v=[],m=y.map(function(t,e){if("unstacked"===t.key)return t.values;var r=t.values[0].r.map(function(t,e){return 0});return t.values.forEach(function(t,e,n){t.yStack=[r],v.push(r),r=o.util.sumArrays(t.r,r)}),t.values});p=n.merge(m)}p.forEach(function(t,e){t.t=Array.isArray(t.t[0])?t.t:[t.t],t.r=Array.isArray(t.r[0])?t.r:[t.r]});var x=Math.min(d.width-d.margin.left-d.margin.right,d.height-d.margin.top-d.margin.bottom)/2;x=Math.max(10,x);var b,_=[d.margin.left+x,d.margin.top+x];b=h?[0,n.max(o.util.sumArrays(o.util.arrayLast(p).r[0],o.util.arrayLast(v)))]:n.extent(o.util.flattenArray(p.map(function(t,e){return t.r}))),d.radialAxis.domain!=o.DATAEXTENT&&(b[0]=0),r=n.scale.linear().domain(d.radialAxis.domain!=o.DATAEXTENT&&d.radialAxis.domain?d.radialAxis.domain:b).range([0,x]),u.layout.radialAxis.domain=r.domain();var w,k=o.util.flattenArray(p.map(function(t,e){return t.t})),M="string"==typeof k[0];M&&(k=o.util.deduplicate(k),w=k.slice(),k=n.range(k.length),p=p.map(function(t,e){var r=t;return t.t=[k],h&&(r.yStack=t.yStack),r}));var T=p.filter(function(t,e){return"LinePlot"===t.geometry||"DotPlot"===t.geometry}).length===p.length,A=null===d.needsEndSpacing?M||!T:d.needsEndSpacing,L=d.angularAxis.domain&&d.angularAxis.domain!=o.DATAEXTENT&&!M&&d.angularAxis.domain[0]>=0?d.angularAxis.domain:n.extent(k),C=Math.abs(k[1]-k[0]);T&&!M&&(C=0);var S=L.slice();A&&M&&(S[1]+=C);var O=d.angularAxis.ticksCount||4;O>8&&(O=O/(O/8)+O%8),d.angularAxis.ticksStep&&(O=(S[1]-S[0])/O);var P=d.angularAxis.ticksStep||(S[1]-S[0])/(O*(d.minorTicks+1));w&&(P=Math.max(Math.round(P),1)),S[2]||(S[2]=P);var D=n.range.apply(this,S);if(D=D.map(function(t,e){return parseFloat(t.toPrecision(12))}),l=n.scale.linear().domain(S.slice(0,2)).range("clockwise"===d.direction?[0,360]:[360,0]),u.layout.angularAxis.domain=l.domain(),u.layout.angularAxis.endPadding=A?C:0,"undefined"==typeof(t=n.select(this).select("svg.chart-root"))||t.empty()){var z=(new DOMParser).parseFromString("<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>","application/xml"),E=this.appendChild(this.ownerDocument.importNode(z.documentElement,!0));t=n.select(E)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var I,N=t.select(".chart-group"),R={fill:"none",stroke:d.tickColor},F={"font-size":d.font.size,"font-family":d.font.family,fill:d.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+d.font.outlineColor}).join(",")};if(d.showLegend){I=t.select(".legend-group").attr({transform:"translate("+[x,d.margin.top]+")"}).style({display:"block"});var j=p.map(function(t,e){var r=o.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});o.Legend().config({data:p.map(function(t,e){return t.name||"Element"+e}),legendConfig:a({},o.Legend.defaultConfig().legendConfig,{container:I,elements:j,reverseOrder:d.legend.reverseOrder})})();var B=I.node().getBBox();x=Math.min(d.width-B.width-d.margin.left-d.margin.right,d.height-d.margin.top-d.margin.bottom)/2,x=Math.max(10,x),_=[d.margin.left+x,d.margin.top+x],r.range([0,x]),u.layout.radialAxis.domain=r.domain(),I.attr("transform","translate("+[_[0]+x,_[1]-x]+")")}else I=t.select(".legend-group").style({display:"none"});t.attr({width:d.width,height:d.height}).style({opacity:d.opacity}),N.attr("transform","translate("+_+")").style({cursor:"crosshair"});var H=[(d.width-(d.margin.left+d.margin.right+2*x+(B?B.width:0)))/2,(d.height-(d.margin.top+d.margin.bottom+2*x))/2];if(H[0]=Math.max(0,H[0]),H[1]=Math.max(0,H[1]),t.select(".outer-group").attr("transform","translate("+H+")"),d.title){var q=t.select("g.title-group text").style(F).text(d.title),V=q.node().getBBox();q.attr({x:_[0]-V.width/2,y:_[1]-x-20})}var U=t.select(".radial.axis-group");if(d.radialAxis.gridLinesVisible){var G=U.selectAll("circle.grid-circle").data(r.ticks(5));G.enter().append("circle").attr({class:"grid-circle"}).style(R),G.attr("r",r),G.exit().remove()}U.select("circle.outside-circle").attr({r:x}).style(R);var Y=t.select("circle.background-circle").attr({r:x}).style({fill:d.backgroundColor,stroke:d.stroke});function X(t,e){return l(t)%360+d.orientation}if(d.radialAxis.visible){var Z=n.svg.axis().scale(r).ticks(5).tickSize(5);U.call(Z).attr({transform:"rotate("+d.radialAxis.orientation+")"}),U.selectAll(".domain").style(R),U.selectAll("g>text").text(function(t,e){return this.textContent+d.radialAxis.ticksSuffix}).style(F).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===d.radialAxis.tickOrientation?"rotate("+-d.radialAxis.orientation+") translate("+[0,F["font-size"]]+")":"translate("+[0,F["font-size"]]+")"}}),U.selectAll("g>line").style({stroke:"black"})}var W=t.select(".angular.axis-group").selectAll("g.angular-tick").data(D),Q=W.enter().append("g").classed("angular-tick",!0);W.attr({transform:function(t,e){return"rotate("+X(t)+")"}}).style({display:d.angularAxis.visible?"block":"none"}),W.exit().remove(),Q.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(d.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(d.minorTicks+1)==0)}).style(R),Q.selectAll(".minor").style({stroke:d.minorTickColor}),W.select("line.grid-line").attr({x1:d.tickLength?x-d.tickLength:0,x2:x}).style({display:d.angularAxis.gridLinesVisible?"block":"none"}),Q.append("text").classed("axis-text",!0).style(F);var J=W.select("text.axis-text").attr({x:x+d.labelOffset,dy:i+"em",transform:function(t,e){var r=X(t),n=x+d.labelOffset,a=d.angularAxis.tickOrientation;return"horizontal"==a?"rotate("+-r+" "+n+" 0)":"radial"==a?r<270&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(r<=180&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:d.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(d.minorTicks+1)!=0?"":w?w[t]+d.angularAxis.ticksSuffix:t+d.angularAxis.ticksSuffix}).style(F);d.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(d.minorTicks+1)!=0?"":d.angularAxis.rewriteTicks(this.textContent,e)});var $=n.max(N.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));I.attr({transform:"translate("+[x+$,d.margin.top]+")"});var K=t.select("g.geometry-group").selectAll("g").size()>0,tt=t.select("g.geometry-group").selectAll("g.geometry").data(p);if(tt.enter().append("g").attr({class:function(t,e){return"geometry geometry"+e}}),tt.exit().remove(),p[0]||K){var et=[];p.forEach(function(t,e){var n={};n.radialScale=r,n.angularScale=l,n.container=tt.filter(function(t,r){return r==e}),n.geometry=t.geometry,n.orientation=d.orientation,n.direction=d.direction,n.index=e,et.push({data:t,geometryConfig:n})});var rt=n.nest().key(function(t,e){return"undefined"!=typeof t.data.groupId||"unstacked"}).entries(et),nt=[];rt.forEach(function(t,e){"unstacked"===t.key?nt=nt.concat(t.values.map(function(t,e){return[t]})):nt.push(t.values)}),nt.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return a(o[r].defaultConfig(),t)});o[r]().config(n)()})}var at,it,ot=t.select(".guides-group"),lt=t.select(".tooltips-group"),st=o.tooltipPanel().config({container:lt,fontSize:8})(),ct=o.tooltipPanel().config({container:lt,fontSize:8})(),ut=o.tooltipPanel().config({container:lt,hasTick:!0})();if(!M){var ft=ot.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});N.on("mousemove.angular-guide",function(t,e){var r=o.util.getMousePos(Y).angle;ft.attr({x2:-x,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-d.orientation)%360;at=l.invert(n);var a=o.util.convertToCartesian(x+12,r+180);st.text(o.util.round(at)).move([a[0]+_[0],a[1]+_[1]])}).on("mouseout.angular-guide",function(t,e){ot.select("line").style({opacity:0})})}var dt=ot.select("circle").style({stroke:"grey",fill:"none"});N.on("mousemove.radial-guide",function(t,e){var n=o.util.getMousePos(Y).radius;dt.attr({r:n}).style({opacity:.5}),it=r.invert(o.util.getMousePos(Y).radius);var a=o.util.convertToCartesian(n,d.radialAxis.orientation);ct.text(o.util.round(it)).move([a[0]+_[0],a[1]+_[1]])}).on("mouseout.radial-guide",function(t,e){dt.style({opacity:0}),ut.hide(),st.hide(),ct.hide()}),t.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(e,r){var a=n.select(this),i=this.style.fill,l="black",s=this.style.opacity||1;if(a.attr({"data-opacity":s}),i&&"none"!==i){a.attr({"data-fill":i}),l=n.hsl(i).darker().toString(),a.style({fill:l,opacity:1});var c={t:o.util.round(e[0]),r:o.util.round(e[1])};M&&(c.t=w[e[0]]);var u="t: "+c.t+", r: "+c.r,f=this.getBoundingClientRect(),d=t.node().getBoundingClientRect(),p=[f.left+f.width/2-H[0]-d.left,f.top+f.height/2-H[1]-d.top];ut.config({color:l}).text(u),ut.move(p)}else i=this.style.stroke||"black",a.attr({"data-stroke":i}),l=n.hsl(i).darker().toString(),a.style({stroke:l,opacity:1})}).on("mousemove.tooltip",function(t,e){if(0!=n.event.which)return!1;n.select(this).attr("data-fill")&&ut.show()}).on("mouseout.tooltip",function(t,e){ut.hide();var r=n.select(this),a=r.attr("data-fill");a?r.style({fill:a,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})})}(c),this},d.config=function(t){if(!arguments.length)return s;var e=o.util.cloneJson(t);return e.data.forEach(function(t,e){s.data[e]||(s.data[e]={}),a(s.data[e],o.Axis.defaultConfig().data[0]),a(s.data[e],t)}),a(s.layout,o.Axis.defaultConfig().layout),a(s.layout,e.layout),this},d.getLiveConfig=function(){return u},d.getinputConfig=function(){return c},d.radialScale=function(t){return r},d.angularScale=function(t){return l},d.svg=function(){return t},n.rebind(d,f,"on"),d},o.Axis.defaultConfig=function(t,e){return{data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:n.scale.category10().range(),title:null,height:450,width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}}},o.util={},o.DATAEXTENT="dataExtent",o.AREA="AreaChart",o.LINE="LinePlot",o.DOT="DotPlot",o.BAR="BarChart",o.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},o.util._extend=function(t,e){for(var r in t)e[r]=t[r]},o.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},o.util.dataFromEquation2=function(t,e){var r=e||6;return n.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180;return[e,t(n)]})},o.util.dataFromEquation=function(t,e,r){var a=e||6,i=[],o=[];n.range(0,360+a,a).forEach(function(e,r){var n=e*Math.PI/180,a=t(n);i.push(e),o.push(a)});var l={t:i,r:o};return r&&(l.name=r),l},o.util.ensureArray=function(t,e){if("undefined"==typeof t)return null;var r=[].concat(t);return n.range(e).map(function(t,e){return r[e]||r[0]})},o.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=o.util.ensureArray(t[e],r)}),t},o.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},o.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},o.util.sumArrays=function(t,e){return n.zip(t,e).map(function(t,e){return n.sum(t)})},o.util.arrayLast=function(t){return t[t.length-1]},o.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},o.util.flattenArray=function(t){for(var e=[];!o.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},o.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},o.util.convertToCartesian=function(t,e){var r=e*Math.PI/180;return[t*Math.cos(r),t*Math.sin(r)]},o.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},o.util.getMousePos=function(t){var e=n.mouse(t.node()),r=e[0],a=e[1],i={};return i.x=r,i.y=a,i.pos=e,i.angle=180*(Math.atan2(a,r)+Math.PI)/Math.PI,i.radius=Math.sqrt(r*r+a*a),i},o.util.duplicatesCount=function(t){for(var e,r={},n={},a=0,i=t.length;a<i;a++)(e=t[a])in r?(r[e]++,n[e]=r[e]):r[e]=1;return n},o.util.duplicates=function(t){return Object.keys(o.util.duplicatesCount(t))},o.util.translator=function(t,e,r,n){if(n){var a=r.slice();r=e,e=a}var i=e.reduce(function(t,e){if("undefined"!=typeof t)return t[e]},t);"undefined"!=typeof i&&(e.reduce(function(t,r,n){if("undefined"!=typeof t)return n===e.length-1&&delete t[r],t[r]},t),r.reduce(function(t,e,n){return"undefined"==typeof t[e]&&(t[e]={}),n===r.length-1&&(t[e]=i),t[e]},t))},o.PolyChart=function(){var t=[o.PolyChart.defaultConfig()],e=n.dispatch("hover"),r={solid:"none",dash:[5,2],dot:[2,5]};function i(){var e=t[0].geometryConfig,a=e.container;"string"==typeof a&&(a=n.select(a)),a.datum(t).each(function(t,a){var i=!!t[0].data.yStack,o=t.map(function(t,e){return i?n.zip(t.data.t[0],t.data.r[0],t.data.yStack[0]):n.zip(t.data.t[0],t.data.r[0])}),l=e.angularScale,s=e.radialScale.domain()[0],c={bar:function(r,a,i){var o=t[i].data,s=e.radialScale(r[1])-e.radialScale(0),c=e.radialScale(r[2]||0),u=o.barWidth;n.select(this).attr({class:"mark bar",d:"M"+[[s+c,-u/2],[s+c,u/2],[c,u/2],[c,-u/2]].join("L")+"Z",transform:function(t,r){return"rotate("+(e.orientation+l(t[0]))+")"}})}};c.dot=function(r,a,i){var o=r[2]?[r[0],r[1]+r[2]]:r,l=n.svg.symbol().size(t[i].data.dotSize).type(t[i].data.dotType)(r,a);n.select(this).attr({class:"mark dot",d:l,transform:function(t,r){var n,a,i,l=(n=function(t,r){var n=e.radialScale(t[1]),a=(e.angularScale(t[0])+e.orientation)*Math.PI/180;return{r:n,t:a}}(o),a=n.r*Math.cos(n.t),i=n.r*Math.sin(n.t),{x:a,y:i});return"translate("+[l.x,l.y]+")"}})};var u=n.svg.line.radial().interpolate(t[0].data.lineInterpolation).radius(function(t){return e.radialScale(t[1])}).angle(function(t){return e.angularScale(t[0])*Math.PI/180});c.line=function(r,a,i){var l=r[2]?o[i].map(function(t,e){return[t[0],t[1]+t[2]]}):o[i];if(n.select(this).each(c.dot).style({opacity:function(e,r){return+t[i].data.dotVisible},fill:h.stroke(r,a,i)}).attr({class:"mark dot"}),!(a>0)){var s=n.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({class:"line",d:u(l),transform:function(t,r){return"rotate("+(e.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return h.fill(r,a,i)},"fill-opacity":0,stroke:function(t,e){return h.stroke(r,a,i)},"stroke-width":function(t,e){return h["stroke-width"](r,a,i)},"stroke-dasharray":function(t,e){return h["stroke-dasharray"](r,a,i)},opacity:function(t,e){return h.opacity(r,a,i)},display:function(t,e){return h.display(r,a,i)}})}};var f=e.angularScale.range(),d=Math.abs(f[1]-f[0])/o[0].length*Math.PI/180,p=n.svg.arc().startAngle(function(t){return-d/2}).endAngle(function(t){return d/2}).innerRadius(function(t){return e.radialScale(s+(t[2]||0))}).outerRadius(function(t){return e.radialScale(s+(t[2]||0))+e.radialScale(t[1])});c.arc=function(t,r,a){n.select(this).attr({class:"mark arc",d:p,transform:function(t,r){return"rotate("+(e.orientation+l(t[0])+90)+")"}})};var h={fill:function(e,r,n){return t[n].data.color},stroke:function(e,r,n){return t[n].data.strokeColor},"stroke-width":function(e,r,n){return t[n].data.strokeSize+"px"},"stroke-dasharray":function(e,n,a){return r[t[a].data.strokeDash]},opacity:function(e,r,n){return t[n].data.opacity},display:function(e,r,n){return"undefined"==typeof t[n].data.visible||t[n].data.visible?"block":"none"}},g=n.select(this).selectAll("g.layer").data(o);g.enter().append("g").attr({class:"layer"});var y=g.selectAll("path.mark").data(function(t,e){return t});y.enter().append("path").attr({class:"mark"}),y.style(h).each(c[e.geometryType]),y.exit().remove(),g.exit().remove()})}return i.config=function(e){return arguments.length?(e.forEach(function(e,r){t[r]||(t[r]={}),a(t[r],o.PolyChart.defaultConfig()),a(t[r],e)}),this):t},i.getColorScale=function(){},n.rebind(i,e,"on"),i},o.PolyChart.defaultConfig=function(){return{data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:n.scale.category20()}}},o.BarChart=function(){return o.PolyChart()},o.BarChart.defaultConfig=function(){return{geometryConfig:{geometryType:"bar"}}},o.AreaChart=function(){return o.PolyChart()},o.AreaChart.defaultConfig=function(){return{geometryConfig:{geometryType:"arc"}}},o.DotPlot=function(){return o.PolyChart()},o.DotPlot.defaultConfig=function(){return{geometryConfig:{geometryType:"dot",dotType:"circle"}}},o.LinePlot=function(){return o.PolyChart()},o.LinePlot.defaultConfig=function(){return{geometryConfig:{geometryType:"line"}}},o.Legend=function(){var t=o.Legend.defaultConfig(),e=n.dispatch("hover");function r(){var e=t.legendConfig,i=t.data.map(function(t,r){return[].concat(t).map(function(t,n){var i=a({},e.elements[r]);return i.name=t,i.color=[].concat(e.elements[r].color)[n],i})}),o=n.merge(i);o=o.filter(function(t,r){return e.elements[r]&&(e.elements[r].visibleInLegend||"undefined"==typeof e.elements[r].visibleInLegend)}),e.reverseOrder&&(o=o.reverse());var l=e.container;("string"==typeof l||l.nodeName)&&(l=n.select(l));var s=o.map(function(t,e){return t.color}),c=e.fontSize,u=null==e.isContinuous?"number"==typeof o[0]:e.isContinuous,f=u?e.height:c*o.length,d=l.classed("legend-group",!0).selectAll("svg").data([0]),p=d.enter().append("svg").attr({width:300,height:f+c,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});p.append("g").classed("legend-axis",!0),p.append("g").classed("legend-marks",!0);var h=n.range(o.length),g=n.scale[u?"linear":"ordinal"]().domain(h).range(s),y=n.scale[u?"linear":"ordinal"]().domain(h)[u?"range":"rangePoints"]([0,f]);if(u){var v=d.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(s);v.enter().append("stop"),v.attr({offset:function(t,e){return e/(s.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),d.append("rect").classed("legend-mark",!0).attr({height:e.height,width:e.colorBandWidth,fill:"url(#grad1)"})}else{var m=d.select(".legend-marks").selectAll("path.legend-mark").data(o);m.enter().append("path").classed("legend-mark",!0),m.attr({transform:function(t,e){return"translate("+[c/2,y(e)+c/2]+")"},d:function(t,e){var r,a,i,o=t.symbol;return i=3*(a=c),"line"===(r=o)?"M"+[[-a/2,-a/12],[a/2,-a/12],[a/2,a/12],[-a/2,a/12]]+"Z":-1!=n.svg.symbolTypes.indexOf(r)?n.svg.symbol().type(r).size(i)():n.svg.symbol().type("square").size(i)()},fill:function(t,e){return g(e)}}),m.exit().remove()}var x=n.svg.axis().scale(y).orient("right"),b=d.select("g.legend-axis").attr({transform:"translate("+[u?e.colorBandWidth:c,c/2]+")"}).call(x);return b.selectAll(".domain").style({fill:"none",stroke:"none"}),b.selectAll("line").style({fill:"none",stroke:u?e.textColor:"none"}),b.selectAll("text").style({fill:e.textColor,"font-size":e.fontSize}).text(function(t,e){return o[e].name}),r}return r.config=function(e){return arguments.length?(a(t,e),this):t},n.rebind(r,e,"on"),r},o.Legend.defaultConfig=function(t,e){return{data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}}},o.tooltipPanel=function(){var t,e,r,i={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},l="tooltip-"+o.tooltipPanel.uid++,s=10,c=function(){var n=(t=i.container.selectAll("g."+l).data([0])).enter().append("g").classed(l,!0).style({"pointer-events":"none",display:"none"});return r=n.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=n.append("text").attr({dx:i.padding+s,dy:.3*+i.fontSize}),c};return c.text=function(a){var o=n.hsl(i.color).l,l=o>=.5?"#aaa":"white",u=o>=.5?"black":"white",f=a||"";e.style({fill:u,"font-size":i.fontSize+"px"}).text(f);var d=i.padding,p=e.node().getBBox(),h={fill:i.color,stroke:l,"stroke-width":"2px"},g=p.width+2*d+s,y=p.height+2*d;return r.attr({d:"M"+[[s,-y/2],[s,-y/4],[i.hasTick?0:s,0],[s,y/4],[s,y/2],[g,y/2],[g,-y/2]].join("L")+"Z"}).style(h),t.attr({transform:"translate("+[s,-y/2+2*d]+")"}),t.style({display:"block"}),c},c.move=function(e){if(t)return t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),c},c.hide=function(){if(t)return t.style({display:"none"}),c},c.show=function(){if(t)return t.style({display:"block"}),c},c.config=function(t){return a(i,t),c},c},o.tooltipPanel.uid=1,o.adapter={},o.adapter.plotly=function(){var t={convert:function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=a({},t);return[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]].forEach(function(t,r){o.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",!0===n.dotVisible?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var i=o.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var n=i.indexOf(t.geometry);-1!=n&&(r.data[e].groupId=n)})}if(t.layout){var l=a({},t.layout);if([[l,["plot_bgcolor"],["backgroundColor"]],[l,["showlegend"],["showLegend"]],[l,["radialaxis"],["radialAxis"]],[l,["angularaxis"],["angularAxis"]],[l.angularaxis,["showline"],["gridLinesVisible"]],[l.angularaxis,["showticklabels"],["labelsVisible"]],[l.angularaxis,["nticks"],["ticksCount"]],[l.angularaxis,["tickorientation"],["tickOrientation"]],[l.angularaxis,["ticksuffix"],["ticksSuffix"]],[l.angularaxis,["range"],["domain"]],[l.angularaxis,["endpadding"],["endPadding"]],[l.radialaxis,["showline"],["gridLinesVisible"]],[l.radialaxis,["tickorientation"],["tickOrientation"]],[l.radialaxis,["ticksuffix"],["ticksSuffix"]],[l.radialaxis,["range"],["domain"]],[l.angularAxis,["showline"],["gridLinesVisible"]],[l.angularAxis,["showticklabels"],["labelsVisible"]],[l.angularAxis,["nticks"],["ticksCount"]],[l.angularAxis,["tickorientation"],["tickOrientation"]],[l.angularAxis,["ticksuffix"],["ticksSuffix"]],[l.angularAxis,["range"],["domain"]],[l.angularAxis,["endpadding"],["endPadding"]],[l.radialAxis,["showline"],["gridLinesVisible"]],[l.radialAxis,["tickorientation"],["tickOrientation"]],[l.radialAxis,["ticksuffix"],["ticksSuffix"]],[l.radialAxis,["range"],["domain"]],[l.font,["outlinecolor"],["outlineColor"]],[l.legend,["traceorder"],["reverseOrder"]],[l,["labeloffset"],["labelOffset"]],[l,["defaultcolorrange"],["defaultColorRange"]]].forEach(function(t,r){o.util.translator.apply(null,t.concat(e))}),e?("undefined"!=typeof l.tickLength&&(l.angularaxis.ticklen=l.tickLength,delete l.tickLength),l.tickColor&&(l.angularaxis.tickcolor=l.tickColor,delete l.tickColor)):(l.angularAxis&&"undefined"!=typeof l.angularAxis.ticklen&&(l.tickLength=l.angularAxis.ticklen),l.angularAxis&&"undefined"!=typeof l.angularAxis.tickcolor&&(l.tickColor=l.angularAxis.tickcolor)),l.legend&&"boolean"!=typeof l.legend.reverseOrder&&(l.legend.reverseOrder="normal"!=l.legend.reverseOrder),l.legend&&"boolean"==typeof l.legend.traceorder&&(l.legend.traceorder=l.legend.traceorder?"reversed":"normal",delete l.legend.reverseOrder),l.margin&&"undefined"!=typeof l.margin.t){var s=["t","r","b","l","pad"],c=["top","right","bottom","left","pad"],u={};n.entries(l.margin).forEach(function(t,e){u[c[s.indexOf(t.key)]]=t.value}),l.margin=u}e&&(delete l.needsEndSpacing,delete l.minorTickColor,delete l.minorTicks,delete l.angularaxis.ticksCount,delete l.angularaxis.ticksCount,delete l.angularaxis.ticksStep,delete l.angularaxis.rewriteTicks,delete l.angularaxis.nticks,delete l.radialaxis.ticksCount,delete l.radialaxis.ticksCount,delete l.radialaxis.ticksStep,delete l.radialaxis.rewriteTicks,delete l.radialaxis.nticks),r.layout=l}return r}};return t}},{"../../../constants/alignment":143,"../../../lib":163,d3:10}],244:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../../lib"),i=t("../../../components/color"),o=t("./micropolar"),l=t("./undo_manager"),s=a.extendDeepAll,c=e.exports={};c.framework=function(t){var e,r,a,i,u,f=new l;function d(r,l){return l&&(u=l),n.select(n.select(u).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),e=e?s(e,r):r,a||(a=o.Axis()),i=o.adapter.plotly().convert(e),a.config(i).render(u),t.data=e.data,t.layout=e.layout,c.fillLayout(t),e}return d.isPolar=!0,d.svg=function(){return a.svg()},d.getConfig=function(){return e},d.getLiveConfig=function(){return o.adapter.plotly().convert(a.getLiveConfig(),!0)},d.getLiveScales=function(){return{t:a.angularScale(),r:a.radialScale()}},d.setUndoPoint=function(){var t,n,a=this,i=o.util.cloneJson(e);t=i,n=r,f.add({undo:function(){n&&a(n)},redo:function(){a(t)}}),r=o.util.cloneJson(i)},d.undo=function(){f.undo()},d.redo=function(){f.redo()},d},c.fillLayout=function(t){var e=n.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:i.background,_container:e,_paperdiv:r,_paper:a};t._fullLayout=s(o,t.layout)}},{"../../../components/color":45,"../../../lib":163,"./micropolar":243,"./undo_manager":245,d3:10}],245:[function(t,e,r){"use strict";e.exports=function(){var t,e=[],r=-1,n=!1;function a(t,e){return t?(n=!0,t[e](),n=!1,this):this}return{add:function(t){return n?this:(e.splice(r+1,e.length-r),e.push(t),r=e.length-1,this)},setCallback:function(e){t=e},undo:function(){var n=e[r];return n?(a(n,"undo"),r-=1,t&&t(n.undo),this):this},redo:function(){var n=e[r+1];return n?(a(n,"redo"),r+=1,t&&t(n.redo),this):this},clear:function(){e=[],r=-1},hasUndo:function(){return-1!==r},hasRedo:function(){return r<e.length-1},getCommands:function(){return e},getPreviousCommand:function(){return e[r-1]},getIndex:function(){return r}}}},{}],246:[function(t,e,r){"use strict";function n(t,e){return"splom"===t?-1:"splom"===e?1:0}e.exports={sortBasePlotModules:function(t,e){return n(t.name,e.name)},sortModules:n}},{}],247:[function(t,e,r){"use strict";var n=t("./lib/loggers"),a=t("./lib/noop"),i=t("./lib/push_unique"),o=t("./lib/is_plain_object"),l=t("./lib/extend"),s=t("./plots/attributes"),c=t("./plots/layout_attributes"),u=l.extendFlat,f=l.extendDeepAll;function d(t){var e=t.name,a=t.categories,i=t.meta;if(r.modules[e])n.log("Type "+e+" already registered");else{r.subplotsRegistry[t.basePlotModule.name]||function(t){var e=t.name;if(r.subplotsRegistry[e])return void n.log("Plot type "+e+" already registered.");for(var a in y(t),r.subplotsRegistry[e]=t,r.componentsRegistry)x(a,t.name)}(t.basePlotModule);for(var o={},l=0;l<a.length;l++)o[a[l]]=!0,r.allCategories[a[l]]=!0;for(var s in r.modules[e]={_module:t,categories:o},i&&Object.keys(i).length&&(r.modules[e].meta=i),r.allTypes.push(e),r.componentsRegistry)v(s,e);t.layoutAttributes&&u(r.traceLayoutAttributes,t.layoutAttributes)}}function p(t){if("string"!=typeof t.name)throw new Error("Component module *name* must be a string.");var e=t.name;for(var n in r.componentsRegistry[e]=t,t.layoutAttributes&&(t.layoutAttributes._isLinkedToArray&&i(r.layoutArrayContainers,e),y(t)),r.modules)v(e,n);for(var a in r.subplotsRegistry)x(e,a);for(var o in r.transformsRegistry)m(e,o);t.schema&&t.schema.layout&&f(c,t.schema.layout)}function h(t){if("string"!=typeof t.name)throw new Error("Transform module *name* must be a string.");var e="Transform module "+t.name,a="function"==typeof t.transform,i="function"==typeof t.calcTransform;if(!a&&!i)throw new Error(e+" is missing a *transform* or *calcTransform* method.");for(var l in a&&i&&n.log([e+" has both a *transform* and *calcTransform* methods.","Please note that all *transform* methods are executed","before all *calcTransform* methods."].join(" ")),o(t.attributes)||n.log(e+" registered without an *attributes* object."),"function"!=typeof t.supplyDefaults&&n.log(e+" registered without a *supplyDefaults* method."),r.transformsRegistry[t.name]=t,r.componentsRegistry)m(l,t.name)}function g(t){var e=t.name,n=e.split("-")[0],a=t.dictionary,i=t.format,o=a&&Object.keys(a).length,l=i&&Object.keys(i).length,s=r.localeRegistry,c=s[e];if(c||(s[e]=c={}),n!==e){var u=s[n];u||(s[n]=u={}),o&&u.dictionary===c.dictionary&&(u.dictionary=a),l&&u.format===c.format&&(u.format=i)}o&&(c.dictionary=a),l&&(c.format=i)}function y(t){if(t.layoutAttributes){var e=t.layoutAttributes._arrayAttrRegexps;if(e)for(var n=0;n<e.length;n++)i(r.layoutArrayRegexes,e[n])}}function v(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.traces){var a=n.traces[e];a&&f(r.modules[e]._module.attributes,a)}}function m(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.transforms){var a=n.transforms[e];a&&f(r.transformsRegistry[e].attributes,a)}}function x(t,e){var n=r.componentsRegistry[t].schema;if(n&&n.subplots){var a=r.subplotsRegistry[e],i=a.layoutAttributes,o="subplot"===a.attr?a.name:a.attr;Array.isArray(o)&&(o=o[0]);var l=n.subplots[o];i&&l&&f(i,l)}}function b(t){return"object"==typeof t&&(t=t.type),t}r.modules={},r.allCategories={},r.allTypes=[],r.subplotsRegistry={},r.transformsRegistry={},r.componentsRegistry={},r.layoutArrayContainers=[],r.layoutArrayRegexes=[],r.traceLayoutAttributes={},r.localeRegistry={},r.apiMethodRegistry={},r.register=function(t){if(!t)throw new Error("No argument passed to Plotly.register.");t&&!Array.isArray(t)&&(t=[t]);for(var e=0;e<t.length;e++){var n=t[e];if(!n)throw new Error("Invalid module was attempted to be registered!");switch(n.moduleType){case"trace":d(n);break;case"transform":h(n);break;case"component":p(n);break;case"locale":g(n);break;case"apiMethod":var a=n.name;r.apiMethodRegistry[a]=n.fn;break;default:throw new Error("Invalid module was attempted to be registered!")}}},r.getModule=function(t){var e=r.modules[b(t)];return!!e&&e._module},r.traceIs=function(t,e){if("various"===(t=b(t)))return!1;var a=r.modules[t];return a||(t&&"area"!==t&&n.log("Unrecognized trace type "+t+"."),a=r.modules[s.type.dflt]),!!a.categories[e]},r.getTransformIndices=function(t,e){for(var r=[],n=t.transforms||[],a=0;a<n.length;a++)n[a].type===e&&r.push(a);return r},r.hasTransform=function(t,e){for(var r=t.transforms||[],n=0;n<r.length;n++)if(r[n].type===e)return!0;return!1},r.getComponentMethod=function(t,e){var n=r.componentsRegistry[t];return n&&n[e]||a},r.call=function(){var t=arguments[0],e=[].slice.call(arguments,1);return r.apiMethodRegistry[t].apply(null,e)}},{"./lib/extend":157,"./lib/is_plain_object":165,"./lib/loggers":168,"./lib/noop":172,"./lib/push_unique":176,"./plots/attributes":204,"./plots/layout_attributes":237}],248:[function(t,e,r){"use strict";var n=t("../lib"),a=n.extendFlat,i=n.extendDeep;function o(t){var e;switch(t){case"themes__thumb":e={autosize:!0,width:150,height:150,title:"",showlegend:!1,margin:{l:5,r:5,t:5,b:5,pad:0},annotations:[]};break;case"thumbnail":e={title:"",hidesources:!0,showlegend:!1,borderwidth:0,bordercolor:"",margin:{l:1,r:1,t:1,b:1,pad:0},annotations:[]};break;default:e={}}return e}e.exports=function(t,e){var r;t.framework&&t.framework.isPolar&&(t=t.framework.getConfig());var n,l=t.data,s=t.layout,c=i([],l),u=i({},s,o(e.tileClass)),f=t._context||{};if(e.width&&(u.width=e.width),e.height&&(u.height=e.height),"thumbnail"===e.tileClass||"themes__thumb"===e.tileClass){u.annotations=[];var d=Object.keys(u);for(r=0;r<d.length;r++)n=d[r],["xaxis","yaxis","zaxis"].indexOf(n.slice(0,5))>-1&&(u[d[r]].title="");for(r=0;r<c.length;r++){var p=c[r];p.showscale=!1,p.marker&&(p.marker.showscale=!1),"pie"===p.type&&(p.textposition="none")}}if(Array.isArray(e.annotations))for(r=0;r<e.annotations.length;r++)u.annotations.push(e.annotations[r]);var h=Object.keys(u).filter(function(t){return t.match(/^scene\d*$/)});if(h.length){var g={};for("thumbnail"===e.tileClass&&(g={title:"",showaxeslabels:!1,showticklabels:!1,linetickenable:!1}),r=0;r<h.length;r++){var y=u[h[r]];y.xaxis||(y.xaxis={}),y.yaxis||(y.yaxis={}),y.zaxis||(y.zaxis={}),a(y.xaxis,g),a(y.yaxis,g),a(y.zaxis,g),y._scene=null}}var v=document.createElement("div");e.tileClass&&(v.className=e.tileClass);var m={gd:v,td:v,layout:u,data:c,config:{staticPlot:void 0===e.staticPlot||e.staticPlot,plotGlPixelRatio:void 0===e.plotGlPixelRatio?2:e.plotGlPixelRatio,displaylogo:e.displaylogo||!1,showLink:e.showLink||!1,showTips:e.showTips||!1,mapboxAccessToken:f.mapboxAccessToken}};return"transparent"!==e.setBackground&&(m.config.setBackground=e.setBackground||"opaque"),m.gd.defaultLayout=o(e.tileClass),m}},{"../lib":163}],249:[function(t,e,r){"use strict";var n=t("../plot_api/to_image"),a=t("../lib"),i=t("./filesaver");e.exports=function(t,e){return(e=e||{}).format=e.format||"png",new Promise(function(r,o){t._snapshotInProgress&&o(new Error("Snapshotting already in progress.")),a.isIE()&&"svg"!==e.format&&o(new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.")),t._snapshotInProgress=!0;var l=n(t,e),s=e.filename||t.fn||"newplot";s+="."+e.format,l.then(function(e){return t._snapshotInProgress=!1,i(e,s)}).then(function(t){r(t)}).catch(function(e){t._snapshotInProgress=!1,o(e)})})}},{"../lib":163,"../plot_api/to_image":200,"./filesaver":250}],250:[function(t,e,r){"use strict";e.exports=function(t,e){var r=document.createElement("a"),n="download"in r,a=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent);return new Promise(function(i,o){if("undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent)&&o(new Error("IE < 10 unsupported")),a&&(document.location.href="data:application/octet-stream"+t.slice(t.search(/[,;]/)),i(e)),e||(e="download"),n&&(r.href=t,r.download=e,document.body.appendChild(r),r.click(),document.body.removeChild(r),i(e)),"undefined"!=typeof navigator&&navigator.msSaveBlob){var l=t.split(/^data:image\/svg\+xml,/)[1],s=decodeURIComponent(l);navigator.msSaveBlob(new Blob([s]),e),i(e)}o(new Error("download error"))})}},{}],251:[function(t,e,r){"use strict";r.getDelay=function(t){return t._has&&(t._has("gl3d")||t._has("gl2d")||t._has("mapbox"))?500:0},r.getRedrawFunc=function(t){var e=t._fullLayout||{};if(!(!(e._has&&e._has("polar"))&&t.data&&t.data[0]&&t.data[0].r))return function(){(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}},{}],252:[function(t,e,r){"use strict";var n=t("./helpers"),a={getDelay:n.getDelay,getRedrawFunc:n.getRedrawFunc,clone:t("./cloneplot"),toSVG:t("./tosvg"),svgToImg:t("./svgtoimg"),toImage:t("./toimage"),downloadImage:t("./download")};e.exports=a},{"./cloneplot":248,"./download":249,"./helpers":251,"./svgtoimg":253,"./toimage":254,"./tosvg":255}],253:[function(t,e,r){"use strict";var n=t("../lib"),a=t("events").EventEmitter;e.exports=function(t){var e=t.emitter||new a,r=new Promise(function(a,i){var o=window.Image,l=t.svg,s=t.format||"png";if(n.isIE()&&"svg"!==s){var c=new Error("Sorry IE does not support downloading from canvas. Try {format:'svg'} instead.");return i(c),t.promise?r:e.emit("error",c)}var u=t.canvas,f=t.scale||1,d=t.width||300,p=t.height||150,h=f*d,g=f*p,y=u.getContext("2d"),v=new o,m="data:image/svg+xml,"+encodeURIComponent(l);u.width=h,u.height=g,v.onload=function(){var r;switch("svg"!==s&&y.drawImage(v,0,0,h,g),s){case"jpeg":r=u.toDataURL("image/jpeg");break;case"png":r=u.toDataURL("image/png");break;case"webp":r=u.toDataURL("image/webp");break;case"svg":r=m;break;default:var n="Image format is not jpeg, png, svg or webp.";if(i(new Error(n)),!t.promise)return e.emit("error",n)}a(r),t.promise||e.emit("success",r)},v.onerror=function(r){if(i(r),!t.promise)return e.emit("error",r)},v.src=m});return t.promise?r:e}},{"../lib":163,events:12}],254:[function(t,e,r){"use strict";var n=t("events").EventEmitter,a=t("../registry"),i=t("../lib"),o=t("./helpers"),l=t("./cloneplot"),s=t("./tosvg"),c=t("./svgtoimg");e.exports=function(t,e){var r=new n,u=l(t,{format:"png"}),f=u.gd;f.style.position="absolute",f.style.left="-5000px",document.body.appendChild(f);var d=o.getRedrawFunc(f);return a.call("plot",f,u.data,u.layout,u.config).then(d).then(function(){var t=o.getDelay(f._fullLayout);setTimeout(function(){var t=s(f),n=document.createElement("canvas");n.id=i.randstr(),(r=c({format:e.format,width:f._fullLayout.width,height:f._fullLayout.height,canvas:n,emitter:r,svg:t})).clean=function(){f&&document.body.removeChild(f)}},t)}).catch(function(t){r.emit("error",t)}),r}},{"../lib":163,"../registry":247,"./cloneplot":248,"./helpers":251,"./svgtoimg":253,"./tosvg":255,events:12}],255:[function(t,e,r){"use strict";var n=t("d3"),a=t("../lib"),i=t("../components/drawing"),o=t("../components/color"),l=t("../constants/xmlns_namespaces"),s=/"/g,c=new RegExp('("TOBESTRIPPED)|(TOBESTRIPPED")',"g");e.exports=function(t,e,r){var u,f=t._fullLayout,d=f._paper,p=f._toppaper,h=f.width,g=f.height;d.insert("rect",":first-child").call(i.setRect,0,0,h,g).call(o.fill,f.paper_bgcolor);var y=f._basePlotModules||[];for(u=0;u<y.length;u++){var v=y[u];v.toSVG&&v.toSVG(t)}if(p){var m=p.node().childNodes,x=Array.prototype.slice.call(m);for(u=0;u<x.length;u++){var b=x[u];b.childNodes.length&&d.node().appendChild(b)}}f._draggers&&f._draggers.remove(),d.node().style.background="",d.selectAll("text").attr({"data-unformatted":null,"data-math":null}).each(function(){var t=n.select(this);if("hidden"!==this.style.visibility&&"none"!==this.style.display){t.style({visibility:null,display:null});var e=this.style.fontFamily;e&&-1!==e.indexOf('"')&&t.style("font-family",e.replace(s,"TOBESTRIPPED"))}else t.remove()}),d.selectAll(".point,.scatterpts").each(function(){var t=n.select(this),e=this.style.fill;e&&-1!==e.indexOf("url(")&&t.style("fill",e.replace(s,"TOBESTRIPPED"))}),"pdf"!==e&&"eps"!==e||d.selectAll("#MathJax_SVG_glyphs path").attr("stroke-width",0),d.node().setAttributeNS(l.xmlns,"xmlns",l.svg),d.node().setAttributeNS(l.xmlns,"xmlns:xlink",l.xlink),"svg"===e&&r&&(d.attr("width",r*h),d.attr("height",r*g),d.attr("viewBox","0 0 "+h+" "+g));var _=(new window.XMLSerializer).serializeToString(d.node());return _=function(t){var e=n.select("body").append("div").style({display:"none"}).html(""),r=t.replace(/(&[^;]*;)/gi,function(t){return"&lt;"===t?"&#60;":"&rt;"===t?"&#62;":-1!==t.indexOf("<")||-1!==t.indexOf(">")?"":e.html(t).text()});return e.remove(),r}(_),_=(_=_.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&amp;")).replace(c,"'"),a.isIE()&&(_=(_=(_=_.replace(/"/gi,"'")).replace(/(\('#)([^']*)('\))/gi,'("#$2")')).replace(/(\\')/gi,'"')),_}},{"../components/color":45,"../components/drawing":70,"../constants/xmlns_namespaces":147,"../lib":163,d3:10}],256:[function(t,e,r){"use strict";var n=t("../../lib").mergeArray;e.exports=function(t,e){for(var r=0;r<t.length;r++)t[r].i=r;n(e.text,t,"tx"),n(e.hovertext,t,"htx");var a=e.marker;if(a){n(a.opacity,t,"mo"),n(a.color,t,"mc");var i=a.line;i&&(n(i.color,t,"mlc"),n(i.width,t,"mlw"))}}},{"../../lib":163}],257:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),a=t("../../components/colorscale/attributes"),i=t("../../components/colorbar/attributes"),o=t("../../plots/font_attributes"),l=t("../../lib/extend").extendFlat,s=o({editType:"calc",arrayOk:!0}),c=l({},n.marker.line.width,{dflt:0}),u=l({width:c,editType:"calc"},a("marker.line")),f=l({line:u,editType:"calc"},a("marker"),{colorbar:i,opacity:{valType:"number",arrayOk:!0,dflt:1,min:0,max:1,editType:"style"}});e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:n.text,hovertext:n.hovertext,textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"none",arrayOk:!0,editType:"calc"},textfont:l({},s,{}),insidetextfont:l({},s,{}),outsidetextfont:l({},s,{}),constraintext:{valType:"enumerated",values:["inside","outside","both","none"],dflt:"both",editType:"calc"},cliponaxis:l({},n.cliponaxis,{}),orientation:{valType:"enumerated",values:["v","h"],editType:"calc+clearAxisTypes"},base:{valType:"any",dflt:null,arrayOk:!0,editType:"calc"},offset:{valType:"number",dflt:null,arrayOk:!0,editType:"calc"},width:{valType:"number",dflt:null,min:0,arrayOk:!0,editType:"calc"},marker:f,selected:{marker:{opacity:n.selected.marker.opacity,color:n.selected.marker.color,editType:"style"},textfont:n.selected.textfont,editType:"style"},unselected:{marker:{opacity:n.unselected.marker.opacity,color:n.unselected.marker.color,editType:"style"},textfont:n.unselected.textfont,editType:"style"},r:n.r,t:n.t,_deprecated:{bardir:{valType:"enumerated",editType:"calc",values:["v","h"]}}}},{"../../components/colorbar/attributes":46,"../../components/colorscale/attributes":52,"../../lib/extend":157,"../../plots/font_attributes":233,"../scatter/attributes":314}],258:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib").isArrayOrTypedArray,i=t("../../plots/cartesian/axes"),o=t("../../components/colorscale/has_colorscale"),l=t("../../components/colorscale/calc"),s=t("./arrays_to_calcdata"),c=t("../scatter/calc_selection");e.exports=function(t,e){var r,u,f,d,p,h=i.getFromId(t,e.xaxis||"x"),g=i.getFromId(t,e.yaxis||"y");"h"===(e.orientation||(e.x&&!e.y?"h":"v"))?(r=h,f=h.makeCalcdata(e,"x"),u=g.makeCalcdata(e,"y"),p=e.xcalendar):(r=g,f=g.makeCalcdata(e,"y"),u=h.makeCalcdata(e,"x"),p=e.ycalendar);var y=Math.min(u.length,f.length),v=new Array(y);for(d=0;d<y;d++)v[d]={p:u[d],s:f[d]},e.ids&&(v[d].id=String(e.ids[d]));var m,x=e.base;if(a(x)){for(d=0;d<Math.min(x.length,v.length);d++)m=r.d2c(x[d],0,p),n(m)?(v[d].b=+m,v[d].hasB=1):v[d].b=0;for(;d<v.length;d++)v[d].b=0}else{m=r.d2c(x,0,p);var b=n(m);for(m=b?m:0,d=0;d<v.length;d++)v[d].b=m,b&&(v[d].hasB=1)}return o(e,"marker")&&l(e,e.marker.color,"marker","c"),o(e,"marker.line")&&l(e,e.marker.line.color,"marker.line","c"),s(v,e),c(v,e),v}},{"../../components/colorscale/calc":53,"../../components/colorscale/has_colorscale":59,"../../lib":163,"../../plots/cartesian/axes":207,"../scatter/calc_selection":316,"./arrays_to_calcdata":256,"fast-isnumeric":13}],259:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../components/color"),i=t("../../registry"),o=t("../scatter/xy_defaults"),l=t("../bar/style_defaults"),s=t("./attributes");e.exports=function(t,e,r,c){function u(r,a){return n.coerce(t,e,s,r,a)}var f=n.coerceFont;if(o(t,e,c,u)){u("orientation",e.x&&!e.y?"h":"v"),u("base"),u("offset"),u("width"),u("text"),u("hovertext");var d=u("textposition"),p=Array.isArray(d)||"auto"===d,h=p||"inside"===d,g=p||"outside"===d;if(h||g){var y=f(u,"textfont",c.font);h&&f(u,"insidetextfont",y),g&&f(u,"outsidetextfont",y),u("constraintext"),u("selected.textfont.color"),u("unselected.textfont.color"),u("cliponaxis")}l(t,e,u,r,c);var v=i.getComponentMethod("errorbars","supplyDefaults");v(t,e,a.defaultLine,{axis:"y"}),v(t,e,a.defaultLine,{axis:"x",inherit:"y"}),n.coerceSelectionMarkerOpacity(e,u)}else e.visible=!1}},{"../../components/color":45,"../../lib":163,"../../registry":247,"../bar/style_defaults":269,"../scatter/xy_defaults":338,"./attributes":257}],260:[function(t,e,r){"use strict";var n=t("../../components/fx"),a=t("../../registry"),i=t("../../components/color"),o=t("../scatter/fill_hover_text");e.exports=function(t,e,r,l){var s,c,u,f,d,p,h,g=t.cd,y=g[0].trace,v=g[0].t,m="closest"===l,x=t.maxHoverDistance,b=t.maxSpikeDistance;function _(t){return t[u]-t.w/2}function w(t){return t[u]+t.w/2}var k=m?_:function(t){return Math.min(_(t),t.p-v.bardelta/2)},M=m?w:function(t){return Math.max(w(t),t.p+v.bardelta/2)};function T(t,e){return n.inbox(t-s,e-s,x+Math.min(1,Math.abs(e-t)/h)-1)}function A(t){return T(k(t),M(t))}function L(t){return n.inbox(t.b-c,t[f]-c,x+(t[f]-c)/(t[f]-t.b)-1)}"h"===y.orientation?(s=r,c=e,u="y",f="x",d=L,p=A):(s=e,c=r,u="x",f="y",p=L,d=A);var C=t[u+"a"],S=t[f+"a"];h=Math.abs(C.r2c(C.range[1])-C.r2c(C.range[0]));var O=n.getDistanceFunction(l,d,p,function(t){return(d(t)+p(t))/2});if(n.getClosest(g,O,t),!1!==t.index){m||(k=function(t){return Math.min(_(t),t.p-v.bargroupwidth/2)},M=function(t){return Math.max(w(t),t.p+v.bargroupwidth/2)});var P=g[t.index],D=P.mcc||y.marker.color,z=P.mlcc||y.marker.line.color,E=P.mlw||y.marker.line.width;i.opacity(D)?t.color=D:i.opacity(z)&&E&&(t.color=z);var I=y.base?P.b+P.s:P.s;t[f+"0"]=t[f+"1"]=S.c2p(P[f],!0),t[f+"LabelVal"]=I;var N=v.extents[v.extents.round(P.p)];return t[u+"0"]=C.c2p(m?k(P):N[0],!0),t[u+"1"]=C.c2p(m?M(P):N[1],!0),t[u+"LabelVal"]=P.p,t.spikeDistance=(L(P)+function(t){return T(_(t),w(t))}(P))/2+b-x,t[u+"Spike"]=C.c2p(P.p,!0),o(P,y,t),a.getComponentMethod("errorbars","hoverInfo")(P,y,t),[t]}}},{"../../components/color":45,"../../components/fx":87,"../../registry":247,"../scatter/fill_hover_text":321}],261:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.setPositions=t("./set_positions"),n.colorbar=t("../scatter/marker_colorbar"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.style=t("./style").style,n.styleOnSelect=t("./style").styleOnSelect,n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="bar",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","bar","oriented","errorBarsOK","showLegend","zoomScale"],n.meta={},e.exports=n},{"../../plots/cartesian":218,"../scatter/marker_colorbar":331,"./arrays_to_calcdata":256,"./attributes":257,"./calc":258,"./defaults":259,"./hover":260,"./layout_attributes":262,"./layout_defaults":263,"./plot":264,"./select":265,"./set_positions":266,"./style":268}],262:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","group","overlay","relative"],dflt:"group",editType:"calc"},barnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:"",editType:"calc"},bargap:{valType:"number",min:0,max:1,editType:"calc"},bargroupgap:{valType:"number",min:0,max:1,dflt:0,editType:"calc"}}},{}],263:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../plots/cartesian/axes"),i=t("../../lib"),o=t("./layout_attributes");e.exports=function(t,e,r){function l(r,n){return i.coerce(t,e,o,r,n)}for(var s=!1,c=!1,u=!1,f={},d=0;d<r.length;d++){var p=r[d];if(n.traceIs(p,"bar")){if(s=!0,"overlay"!==t.barmode&&"stack"!==t.barmode){var h=p.xaxis+p.yaxis;f[h]&&(u=!0),f[h]=!0}if(p.visible&&"histogram"===p.type)"category"!==a.getFromId({_fullLayout:e},p["v"===p.orientation?"xaxis":"yaxis"]).type&&(c=!0)}}s&&("overlay"!==l("barmode")&&l("barnorm"),l("bargap",c&&!u?0:.2),l("bargroupgap"))}},{"../../lib":163,"../../plots/cartesian/axes":207,"../../registry":247,"./layout_attributes":262}],264:[function(t,e,r){"use strict";var n=t("d3"),a=t("fast-isnumeric"),i=t("tinycolor2"),o=t("../../lib"),l=t("../../lib/svg_text_utils"),s=t("../../components/color"),c=t("../../components/drawing"),u=t("../../registry"),f=t("./attributes"),d=f.text,p=f.textposition,h=f.textfont,g=f.insidetextfont,y=f.outsidetextfont,v=3;function m(t,e,r,n,a,i){var o;return a<1?o="scale("+a+") ":(a=1,o=""),"translate("+(r-a*t)+" "+(n-a*e)+")"+o+(i?"rotate("+i+" "+t+" "+e+") ":"")}function x(t,e,r,n){var o=b((e=e||{}).family,r),l=b(e.size,r),s=b(e.color,r);return{family:_(t.family,o,n.family),size:function(t,e,r){if(a(e)){e=+e;var n=t.min,i=t.max,o=void 0!==n&&e<n||void 0!==i&&e>i;if(!o)return e}return void 0!==r?r:t.dflt}(t.size,l,n.size),color:function(t,e,r){return i(e).isValid()?e:void 0!==r?r:t.dflt}(t.color,s,n.color)}}function b(t,e){var r;return Array.isArray(t)?e<t.length&&(r=t[e]):r=t,r}function _(t,e,r){if("string"==typeof e){if(e||!t.noBlank)return e}else if("number"==typeof e&&!t.strict)return String(e);return void 0!==r?r:t.dflt}e.exports=function(t,e,r,i){var f=e.xaxis,w=e.yaxis,k=t._fullLayout,M=i.selectAll("g.trace.bars").data(r,function(t){return t[0].trace.uid});M.enter().append("g").attr("class","trace bars").append("g").attr("class","points"),M.exit().remove(),M.order(),M.each(function(r){var i=r[0],u=i.t,M=i.trace,T=n.select(this);e.isRangePlot||(i.node3=T);var A=u.poffset,L=Array.isArray(A),C=T.select("g.points").selectAll("g.point").data(o.identity);C.enter().append("g").classed("point",!0),C.exit().remove(),C.each(function(i,u){var T,C,S,O,P=n.select(this),D=i.p+(L?A[u]:A),z=D+i.w,E=i.b,I=E+i.s;if("h"===M.orientation?(S=w.c2p(D,!0),O=w.c2p(z,!0),T=f.c2p(E,!0),C=f.c2p(I,!0),i.ct=[C,(S+O)/2]):(T=f.c2p(D,!0),C=f.c2p(z,!0),S=w.c2p(E,!0),O=w.c2p(I,!0),i.ct=[(T+C)/2,O]),a(T)&&a(C)&&a(S)&&a(O)&&T!==C&&S!==O){var N=(i.mlw+1||M.marker.line.width+1||(i.trace?i.trace.marker.line.width:0)+1)-1,R=n.round(N/2%1,2);if(!t._context.staticPlot){var F=s.opacity(i.mc||M.marker.color)<1||N>.01?j:function(t,e){return Math.abs(t-e)>=2?j(t):t>e?Math.ceil(t):Math.floor(t)};T=F(T,C),C=F(C,T),S=F(S,O),O=F(O,S)}o.ensureSingle(P,"path").style("vector-effect","non-scaling-stroke").attr("d","M"+T+","+S+"V"+O+"H"+C+"V"+S+"Z").call(c.setClipUrl,e.layerClipId),function(t,e,r,n,a,i,s,u){var f;function w(e,r,n){var a=o.ensureSingle(e,"text").text(r).attr({class:"bartext bartext-"+f,transform:"","text-anchor":"middle","data-notex":1}).call(c.font,n).call(l.convertToTspans,t);return a}var k=r[0].trace,M=k.orientation,T=function(t,e){var r=b(t.text,e);return _(d,r)}(k,n);if(f=function(t,e){var r=b(t.textposition,e);return function(t,e,r){return t.coerceNumber&&(e=+e),-1!==t.values.indexOf(e)?e:void 0!==r?r:t.dflt}(p,r)}(k,n),!T||"none"===f)return void e.select("text").remove();var A,L,C,S,O,P,D=function(t,e,r){return x(h,t.textfont,e,r)}(k,n,t._fullLayout.font),z=function(t,e,r){return x(g,t.insidetextfont,e,r)}(k,n,D),E=function(t,e,r){return x(y,t.outsidetextfont,e,r)}(k,n,D),I=t._fullLayout.barmode,N="relative"===I,R="stack"===I||N,F=r[n],j=!R||F._outmost,B=Math.abs(i-a)-2*v,H=Math.abs(u-s)-2*v;"outside"===f&&(j||(f="inside"));if("auto"===f)if(j){f="inside",A=w(e,T,z),L=c.bBox(A.node()),C=L.width,S=L.height;var q=C>0&&S>0,V=C<=B&&S<=H,U=C<=H&&S<=B,G="h"===M?B>=C*(H/S):H>=S*(B/C);q&&(V||U||G)?f="inside":(f="outside",A.remove(),A=null)}else f="inside";if(!A&&(A=w(e,T,"outside"===f?E:z),L=c.bBox(A.node()),C=L.width,S=L.height,C<=0||S<=0))return void A.remove();"outside"===f?(P="both"===k.constraintext||"outside"===k.constraintext,O=function(t,e,r,n,a,i,o){var l,s="h"===i?Math.abs(n-r):Math.abs(e-t);s>2*v&&(l=v);var c=1;o&&(c="h"===i?Math.min(1,s/a.height):Math.min(1,s/a.width));var u,f,d,p,h=(a.left+a.right)/2,g=(a.top+a.bottom)/2;u=c*a.width,f=c*a.height,"h"===i?e<t?(d=e-l-u/2,p=(r+n)/2):(d=e+l+u/2,p=(r+n)/2):n>r?(d=(t+e)/2,p=n+l+f/2):(d=(t+e)/2,p=n-l-f/2);return m(h,g,d,p,c,!1)}(a,i,s,u,L,M,P)):(P="both"===k.constraintext||"inside"===k.constraintext,O=function(t,e,r,n,a,i,o){var l,s,c,u,f,d,p,h=a.width,g=a.height,y=(a.left+a.right)/2,x=(a.top+a.bottom)/2,b=Math.abs(e-t),_=Math.abs(n-r);b>2*v&&_>2*v?(b-=2*(f=v),_-=2*f):f=0;h<=b&&g<=_?(d=!1,p=1):h<=_&&g<=b?(d=!0,p=1):h<g==b<_?(d=!1,p=o?Math.min(b/h,_/g):1):(d=!0,p=o?Math.min(_/h,b/g):1);d&&(d=90);d?(l=p*g,s=p*h):(l=p*h,s=p*g);"h"===i?e<t?(c=e+f+l/2,u=(r+n)/2):(c=e-f-l/2,u=(r+n)/2):n>r?(c=(t+e)/2,u=n-f-s/2):(c=(t+e)/2,u=n+f+s/2);return m(y,x,c,u,p,d)}(a,i,s,u,L,M,P));A.attr("transform",O)}(t,P,r,u,T,C,S,O),e.layerClipId&&c.hideOutsideRangePoint(r[u],P.select("text"),f,w,M.xcalendar,M.ycalendar)}else P.remove();function j(t){return 0===k.bargap&&0===k.bargroupgap?n.round(Math.round(t)-R,2):t}});var S=!1===r[0].trace.cliponaxis;c.setClipUrl(T,S?null:e.layerClipId)}),u.getComponentMethod("errorbars","plot")(M,e)}},{"../../components/color":45,"../../components/drawing":70,"../../lib":163,"../../lib/svg_text_utils":184,"../../registry":247,"./attributes":257,d3:10,"fast-isnumeric":13,tinycolor2:28}],265:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n=t.cd,a=t.xaxis,i=t.yaxis,o=[];if(!1===e)for(r=0;r<n.length;r++)n[r].selected=0;else for(r=0;r<n.length;r++){var l=n[r];e.contains(l.ct)?(o.push({pointNumber:r,x:a.c2d(l.x),y:i.c2d(l.y)}),l.selected=1):l.selected=0}return o}},{}],266:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib").isArrayOrTypedArray,i=t("../../constants/numerical").BADNUM,o=t("../../registry"),l=t("../../plots/cartesian/axes"),s=t("./sieve.js");function c(t,e,r,a){if(a.length){var o,c,b,_,w=t._fullLayout.barmode,k="group"===w;if("overlay"===w)u(t,e,r,a);else if(k){for(o=[],c=[],b=0;b<a.length;b++)void 0===(_=a[b])[0].trace.offset?c.push(_):o.push(_);c.length&&function(t,e,r,n){var a=t._fullLayout.barnorm,i=new s(n,!1,!a);(function(t,e,r){var n,a,i,o,l=t._fullLayout,s=l.bargap,c=l.bargroupgap,u=r.positions,f=r.distinctPositions,g=r.minDiff,y=r.traces,v=u.length!==f.length,m=y.length,x=g*(1-s),b=v?x/m:x,_=b*(1-c);for(n=0;n<m;n++){a=y[n],i=a[0];var w=v?((2*n+1-m)*b-_)/2:-_/2;(o=i.t).barwidth=_,o.poffset=w,o.bargroupwidth=x,o.bardelta=g}r.binWidth=y[0][0].t.barwidth/100,d(r),p(t,e,r),h(t,e,r,v)})(t,e,i),a?(v(t,r,i),m(t,r,i)):y(t,r,i)}(t,e,r,c),o.length&&u(t,e,r,o)}else{for(o=[],c=[],b=0;b<a.length;b++)void 0===(_=a[b])[0].trace.base?c.push(_):o.push(_);c.length&&function(t,e,r,a){var o=t._fullLayout.barmode,c="stack"===o,u="relative"===o,d=t._fullLayout.barnorm,p=new s(a,u,!(d||c||u));f(t,e,p),function(t,e,r){var a,o,s,c,u=t._fullLayout.barnorm,f=x(e),d=r.traces,p=[null,null];for(a=0;a<d.length;a++)for(o=d[a],s=0;s<o.length;s++)if((c=o[s]).s!==i){var h=r.put(c.p,c.b+c.s),y=h+c.b+c.s;c.b=h,c[f]=y,u||(n(e.c2l(y))&&g(p,y),c.hasB&&n(e.c2l(h))&&g(p,h))}u||l.expand(e,p,{tozero:!0,padded:!0})}(t,r,p);for(var h=0;h<a.length;h++)for(var y=a[h],v=0;v<y.length;v++){var b=y[v];if(b.s!==i){var _=b.b+b.s===p.get(b.p,b.s);_&&(b._outmost=!0)}}d&&m(t,r,p)}(t,e,r,c),o.length&&u(t,e,r,o)}!function(t,e){var r,a,i,o=e._id.charAt(0),l={},s=1/0,c=-1/0;for(r=0;r<t.length;r++)for(i=t[r],a=0;a<i.length;a++){var u=i[a].p;n(u)&&(s=Math.min(s,u),c=Math.max(c,u))}var f=1e4/(c-s),d=l.round=function(t){return String(Math.round(f*(t-s)))};for(r=0;r<t.length;r++)for((i=t[r])[0].t.extents=l,a=0;a<i.length;a++){var p=i[a],h=p[o]-p.w/2;if(n(h)){var g=p[o]+p.w/2,y=d(p.p);l[y]?l[y]=[Math.min(h,l[y][0]),Math.max(g,l[y][1])]:l[y]=[h,g]}}}(a,e)}}function u(t,e,r,n){for(var a=t._fullLayout.barnorm,i=!a,o=0;o<n.length;o++){var l=n[o],c=new s([l],!1,i);f(t,e,c),a?(v(t,r,c),m(t,r,c)):y(t,r,c)}}function f(t,e,r){var n,a,i=t._fullLayout,o=i.bargap,l=i.bargroupgap,s=r.minDiff,c=r.traces,u=s*(1-o),f=u*(1-l),g=-f/2;for(n=0;n<c.length;n++)(a=c[n][0].t).barwidth=f,a.poffset=g,a.bargroupwidth=u,a.bardelta=s;r.binWidth=c[0][0].t.barwidth/100,d(r),p(t,e,r),h(t,e,r)}function d(t){var e,r,i,o,l,s,c=t.traces;for(e=0;e<c.length;e++){o=(i=(r=c[e])[0]).trace,s=i.t;var u,f=o.offset,d=s.poffset;if(a(f)){for(u=f.slice(0,r.length),l=0;l<u.length;l++)n(u[l])||(u[l]=d);for(l=u.length;l<r.length;l++)u.push(d);s.poffset=u}else void 0!==f&&(s.poffset=f);var p=o.width,h=s.barwidth;if(a(p)){var g=p.slice(0,r.length);for(l=0;l<g.length;l++)n(g[l])||(g[l]=h);for(l=g.length;l<r.length;l++)g.push(h);if(s.barwidth=g,void 0===f){for(u=[],l=0;l<r.length;l++)u.push(d+(h-g[l])/2);s.poffset=u}}else void 0!==p&&(s.barwidth=p,void 0===f&&(s.poffset=d+(h-p)/2))}}function p(t,e,r){for(var n=r.traces,a=x(e),i=0;i<n.length;i++)for(var o=n[i],l=o[0].t,s=l.poffset,c=Array.isArray(s),u=l.barwidth,f=Array.isArray(u),d=0;d<o.length;d++){var p=o[d],h=p.w=f?u[d]:u;p[a]=p.p+(c?s[d]:s)+h/2}}function h(t,e,r,n){var a=r.traces,i=r.distinctPositions,o=i[0],s=r.minDiff,c=s/2;l.minDtick(e,s,o,n);for(var u=Math.min.apply(Math,i)-c,f=Math.max.apply(Math,i)+c,d=0;d<a.length;d++){var p=a[d],h=p[0],g=h.trace;if(void 0!==g.width||void 0!==g.offset)for(var y=h.t,v=y.poffset,m=y.barwidth,x=Array.isArray(v),b=Array.isArray(m),_=0;_<p.length;_++){var w=p[_],k=x?v[_]:v,M=b?m[_]:m,T=w.p+k,A=T+M;u=Math.min(u,T),f=Math.max(f,A)}}l.expand(e,[u,f],{padded:!1})}function g(t,e){n(t[0])?t[0]=Math.min(t[0],e):t[0]=e,n(t[1])?t[1]=Math.max(t[1],e):t[1]=e}function y(t,e,r){for(var a=r.traces,i=x(e),o=[null,null],s=0;s<a.length;s++)for(var c=a[s],u=0;u<c.length;u++){var f=c[u],d=f.b,p=d+f.s;f[i]=p,n(e.c2l(p))&&g(o,p),f.hasB&&n(e.c2l(d))&&g(o,d)}l.expand(e,o,{tozero:!0,padded:!0})}function v(t,e,r){for(var n=r.traces,a=0;a<n.length;a++)for(var o=n[a],l=0;l<o.length;l++){var s=o[l];s.s!==i&&r.put(s.p,s.b+s.s)}}function m(t,e,r){var a=r.traces,o=x(e),s="fraction"===t._fullLayout.barnorm?1:100,c=s/1e9,u=e.l2c(e.c2l(0)),f="stack"===t._fullLayout.barmode?s:u,d=[u,f],p=!1;function h(t){n(e.c2l(t))&&(t<u-c||t>f+c||!n(u))&&(p=!0,g(d,t))}for(var y=0;y<a.length;y++)for(var v=a[y],m=0;m<v.length;m++){var b=v[m];if(b.s!==i){var _=Math.abs(s/r.get(b.p,b.s));b.b*=_,b.s*=_;var w=b.b,k=w+b.s;b[o]=k,h(k),b.hasB&&h(w)}}l.expand(e,d,{tozero:!0,padded:p})}function x(t){return t._id.charAt(0)}e.exports=function(t,e){var r,n=e.xaxis,a=e.yaxis,i=t._fullData,l=t.calcdata,s=[],u=[];for(r=0;r<i.length;r++){var f=i[r];!0===f.visible&&o.traceIs(f,"bar")&&f.xaxis===n._id&&f.yaxis===a._id&&("h"===f.orientation?s.push(l[r]):u.push(l[r]))}c(t,n,a,u),c(t,a,n,s)}},{"../../constants/numerical":145,"../../lib":163,"../../plots/cartesian/axes":207,"../../registry":247,"./sieve.js":267,"fast-isnumeric":13}],267:[function(t,e,r){"use strict";e.exports=i;var n=t("../../lib"),a=t("../../constants/numerical").BADNUM;function i(t,e,r){this.traces=t,this.separateNegativeValues=e,this.dontMergeOverlappingData=r;for(var i=1/0,o=[],l=0;l<t.length;l++){for(var s=t[l],c=0;c<s.length;c++){var u=s[c];u.p!==a&&o.push(u.p)}s[0]&&s[0].width1&&(i=Math.min(s[0].width1,i))}this.positions=o;var f=n.distinctVals(o);this.distinctPositions=f.vals,1===f.vals.length&&i!==1/0?this.minDiff=i:this.minDiff=Math.min(f.minDiff,i),this.binWidth=this.minDiff,this.bins={}}i.prototype.put=function(t,e){var r=this.getLabel(t,e),n=this.bins[r]||0;return this.bins[r]=n+e,n},i.prototype.get=function(t,e){var r=this.getLabel(t,e);return this.bins[r]||0},i.prototype.getLabel=function(t,e){return(e<0&&this.separateNegativeValues?"v":"^")+(this.dontMergeOverlappingData?t:Math.round(t/this.binWidth))}},{"../../constants/numerical":145,"../../lib":163}],268:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/drawing"),i=t("../../registry");function o(t,e,r){var i=t.selectAll("path"),o=t.selectAll("text");a.pointStyle(i,e,r),o.each(function(t){var r,i=n.select(this);function o(e){var n=r[e];return Array.isArray(n)?n[t.i]:n}i.classed("bartext-inside")?r=e.insidetextfont:i.classed("bartext-outside")&&(r=e.outsidetextfont),r||(r=e.textfont),a.font(i,o("family"),o("size"),o("color"))})}e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.bars"),a=r.size(),l=t._fullLayout;r.style("opacity",function(t){return t[0].trace.opacity}).each(function(t){("stack"===l.barmode&&a>1||0===l.bargap&&0===l.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),r.selectAll("g.points").each(function(e){o(n.select(this),e[0].trace,t)}),i.getComponentMethod("errorbars","style")(r)},styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace;n.selectedpoints?(a.selectedPointStyle(r.selectAll("path"),n),a.selectedTextStyle(r.selectAll("text"),n)):o(r,n,t)}}},{"../../components/drawing":70,"../../registry":247,d3:10}],269:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,l){r("marker.color",o),a(t,"marker")&&i(t,e,l,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),a(t,"marker.line")&&i(t,e,l,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width"),r("marker.opacity"),r("selected.marker.color"),r("unselected.marker.color")}},{"../../components/color":45,"../../components/colorscale/defaults":55,"../../components/colorscale/has_colorscale":59}],270:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),a=t("../../components/color/attributes"),i=t("../../lib/extend").extendFlat,o=n.marker,l=o.line;e.exports={y:{valType:"data_array",editType:"calc+clearAxisTypes"},x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",editType:"calc+clearAxisTypes"},y0:{valType:"any",editType:"calc+clearAxisTypes"},name:{valType:"string",editType:"calc+clearAxisTypes"},text:i({},n.text,{}),whiskerwidth:{valType:"number",min:0,max:1,dflt:.5,editType:"calcIfAutorange"},notched:{valType:"boolean",editType:"calcIfAutorange"},notchwidth:{valType:"number",min:0,max:.5,dflt:.25,editType:"calcIfAutorange"},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers",editType:"calcIfAutorange"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1,editType:"calcIfAutorange"},jitter:{valType:"number",min:0,max:1,editType:"calcIfAutorange"},pointpos:{valType:"number",min:-2,max:2,editType:"calcIfAutorange"},orientation:{valType:"enumerated",values:["v","h"],editType:"calc+clearAxisTypes"},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)",editType:"style"},symbol:i({},o.symbol,{arrayOk:!1,editType:"plot"}),opacity:i({},o.opacity,{arrayOk:!1,dflt:1,editType:"style"}),size:i({},o.size,{arrayOk:!1,editType:"calcIfAutorange"}),color:i({},o.color,{arrayOk:!1,editType:"style"}),line:{color:i({},l.color,{arrayOk:!1,dflt:a.defaultLine,editType:"style"}),width:i({},l.width,{arrayOk:!1,dflt:0,editType:"style"}),outliercolor:{valType:"color",editType:"style"},outlierwidth:{valType:"number",min:0,dflt:1,editType:"style"},editType:"style"},editType:"plot"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},editType:"plot"},fillcolor:n.fillcolor,selected:{marker:n.selected.marker,editType:"style"},unselected:{marker:n.unselected.marker,editType:"style"},hoveron:{valType:"flaglist",flags:["boxes","points"],dflt:"boxes+points",editType:"style"}}},{"../../components/color/attributes":44,"../../lib/extend":157,"../scatter/attributes":314}],271:[function(t,e,r){"use strict";e.exports={boxmode:{valType:"enumerated",values:["group","overlay"],dflt:"overlay",editType:"calc"},boxgap:{valType:"number",min:0,max:1,dflt:.3,editType:"calc"},boxgroupgap:{valType:"number",min:0,max:1,dflt:.3,editType:"calc"}}},{}],272:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("./layout_attributes");function o(t,e,r,a,i){for(var o,l=i+"Layout",s=0;s<r.length;s++)if(n.traceIs(r[s],l)){o=!0;break}o&&(a(i+"mode"),a(i+"gap"),a(i+"groupgap"))}e.exports={supplyLayoutDefaults:function(t,e,r){o(0,0,r,function(r,n){return a.coerce(t,e,i,r,n)},"box")},_supply:o}},{"../../lib":163,"../../registry":247,"./layout_attributes":271}],273:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../lib"),i=t("../../components/drawing"),o=5,l=.01;function s(t,e,r,i){var o,l,s=e.pos,c=e.val,u=i.bPos,f=i.wdPos||0,d=i.bPosPxOffset||0,p=r.whiskerwidth||0,h=r.notched||!1,g=h?1-2*r.notchwidth:1;Array.isArray(i.bdPos)?(o=i.bdPos[0],l=i.bdPos[1]):(o=i.bdPos,l=i.bdPos);var y=t.selectAll("path.box").data("violin"!==r.type||r.box?a.identity:[]);y.enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","box"),y.exit().remove(),y.each(function(t){var e=t.pos,i=s.c2p(e+u,!0)+d,y=s.c2p(e+u-o,!0)+d,v=s.c2p(e+u+l,!0)+d,m=s.c2p(e+u-f,!0)+d,x=s.c2p(e+u+f,!0)+d,b=s.c2p(e+u-o*g,!0)+d,_=s.c2p(e+u+l*g,!0)+d,w=c.c2p(t.q1,!0),k=c.c2p(t.q3,!0),M=a.constrain(c.c2p(t.med,!0),Math.min(w,k)+1,Math.max(w,k)-1),T=void 0===t.lf||!1===r.boxpoints,A=c.c2p(T?t.min:t.lf,!0),L=c.c2p(T?t.max:t.uf,!0),C=c.c2p(t.ln,!0),S=c.c2p(t.un,!0);"h"===r.orientation?n.select(this).attr("d","M"+M+","+b+"V"+_+"M"+w+","+y+"V"+v+(h?"H"+C+"L"+M+","+_+"L"+S+","+v:"")+"H"+k+"V"+y+(h?"H"+S+"L"+M+","+b+"L"+C+","+y:"")+"ZM"+w+","+i+"H"+A+"M"+k+","+i+"H"+L+(0===p?"":"M"+A+","+m+"V"+x+"M"+L+","+m+"V"+x)):n.select(this).attr("d","M"+b+","+M+"H"+_+"M"+y+","+w+"H"+v+(h?"V"+C+"L"+_+","+M+"L"+v+","+S:"")+"V"+k+"H"+y+(h?"V"+S+"L"+b+","+M+"L"+y+","+C:"")+"ZM"+i+","+w+"V"+A+"M"+i+","+k+"V"+L+(0===p?"":"M"+m+","+A+"H"+x+"M"+m+","+L+"H"+x))})}function c(t,e,r,n){var s=e.x,c=e.y,u=n.bdPos,f=n.bPos,d=r.boxpoints||r.points;a.seedPseudoRandom();var p=t.selectAll("g.points").data(d?function(t){return t.forEach(function(t){t.t=n,t.trace=r}),t}:[]);p.enter().append("g").attr("class","points"),p.exit().remove();var h=p.selectAll("path").data(function(t){var e,n,i="all"===d?t.pts:t.pts.filter(function(e){return e.v<t.lf||e.v>t.uf}),s=Math.max((t.max-t.min)/10,t.q3-t.q1),c=1e-9*s,p=s*l,h=[],g=0;if(r.jitter){if(0===s)for(g=1,h=new Array(i.length),e=0;e<i.length;e++)h[e]=1;else for(e=0;e<i.length;e++){var y=Math.max(0,e-o),v=i[y].v,m=Math.min(i.length-1,e+o),x=i[m].v;"all"!==d&&(i[e].v<t.lf?x=Math.min(x,t.lf):v=Math.max(v,t.uf));var b=Math.sqrt(p*(m-y)/(x-v+c))||0;b=a.constrain(Math.abs(b),0,1),h.push(b),g=Math.max(b,g)}n=2*r.jitter/(g||1)}for(e=0;e<i.length;e++){var _=i[e],w=_.v,k=r.jitter?n*h[e]*(a.pseudoRandom()-.5):0,M=t.pos+f+u*(r.pointpos+k);"h"===r.orientation?(_.y=M,_.x=w):(_.x=M,_.y=w),"suspectedoutliers"===d&&w<t.uo&&w>t.lo&&(_.so=!0)}return i});h.enter().append("path").classed("point",!0),h.exit().remove(),h.call(i.translatePoints,s,c)}function u(t,e,r,i){var o,l,s=e.pos,c=e.val,u=i.bPos,f=i.bPosPxOffset||0,d=r.boxmean||(r.meanline||{}).visible;Array.isArray(i.bdPos)?(o=i.bdPos[0],l=i.bdPos[1]):(o=i.bdPos,l=i.bdPos);var p=t.selectAll("path.mean").data("box"===r.type&&r.boxmean||"violin"===r.type&&r.box&&r.meanline?a.identity:[]);p.enter().append("path").attr("class","mean").style({fill:"none","vector-effect":"non-scaling-stroke"}),p.exit().remove(),p.each(function(t){var e=s.c2p(t.pos+u,!0)+f,a=s.c2p(t.pos+u-o,!0)+f,i=s.c2p(t.pos+u+l,!0)+f,p=c.c2p(t.mean,!0),h=c.c2p(t.mean-t.sd,!0),g=c.c2p(t.mean+t.sd,!0);"h"===r.orientation?n.select(this).attr("d","M"+p+","+a+"V"+i+("sd"===d?"m0,0L"+h+","+e+"L"+p+","+a+"L"+g+","+e+"Z":"")):n.select(this).attr("d","M"+a+","+p+"H"+i+("sd"===d?"m0,0L"+e+","+h+"L"+a+","+p+"L"+e+","+g+"Z":""))})}e.exports={plot:function(t,e,r,a){var i=t._fullLayout,o=e.xaxis,l=e.yaxis,f=a.selectAll("g.trace.boxes").data(r,function(t){return t[0].trace.uid});f.enter().append("g").attr("class","trace boxes"),f.exit().remove(),f.order(),f.each(function(t){var r=t[0],a=r.t,f=r.trace,d=n.select(this);e.isRangePlot||(r.node3=d);var p,h,g=i._numBoxes,y=1-i.boxgap,v="group"===i.boxmode&&g>1,m=a.dPos*y*(1-i.boxgroupgap)/(v?g:1),x=v?2*a.dPos*((a.num+.5)/g-.5)*y:0,b=m*f.whiskerwidth;!0!==f.visible||a.empty?d.remove():("h"===f.orientation?(p=l,h=o):(p=o,h=l),a.bPos=x,a.bdPos=m,a.wdPos=b,a.wHover=a.dPos*(v?y/g:1),s(d,{pos:p,val:h},f,a),c(d,{x:o,y:l},f,a),u(d,{pos:p,val:h},f,a))})},plotBoxAndWhiskers:s,plotPoints:c,plotBoxMean:u}},{"../../components/drawing":70,"../../lib":163,d3:10}],274:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),a=t("../../lib"),i=["v","h"];function o(t,e,r,i,o){var l,s,c,u=e.calcdata,f=e._fullLayout,d=[],p="violin"===t?"_numViolins":"_numBoxes";for(l=0;l<r.length;l++)for(c=u[r[l]],s=0;s<c.length;s++)d.push(c[s].pos);if(d.length){var h=a.distinctVals(d),g=h.minDiff/2;for(d.length===h.vals.length&&(f[p]=1),n.minDtick(i,h.minDiff,h.vals[0],!0),l=0;l<r.length;l++)(c=u[r[l]])[0].t.dPos=g;var y=(1-f[t+"gap"])*(1-f[t+"groupgap"])*g/f[p];n.expand(i,h.vals,{vpadminus:g+o[0]*y,vpadplus:g+o[1]*y})}}e.exports={setPositions:function(t,e){for(var r=t.calcdata,n=e.xaxis,a=e.yaxis,l=0;l<i.length;l++){for(var s=i[l],c="h"===s?a:n,u=[],f=0,d=0,p=0;p<r.length;p++){var h=r[p],g=h[0].t,y=h[0].trace;!0!==y.visible||"box"!==y.type&&"candlestick"!==y.type||g.empty||(y.orientation||"v")!==s||y.xaxis!==n._id||y.yaxis!==a._id||(u.push(p),y.boxpoints&&(f=Math.max(f,y.jitter-y.pointpos-1),d=Math.max(d,y.jitter+y.pointpos-1)))}o("box",t,u,c,[f,d])}},setPositionOffset:o}},{"../../lib":163,"../../plots/cartesian/axes":207}],275:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/color"),i=t("../../components/drawing");e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.boxes");r.style("opacity",function(t){return t[0].trace.opacity}),r.each(function(e){var r=n.select(this),o=e[0].trace,l=o.line.width;function s(t,e,r,n){t.style("stroke-width",e+"px").call(a.stroke,r).call(a.fill,n)}var c=r.selectAll("path.box");if("candlestick"===o.type)c.each(function(t){var e=n.select(this),r=o[t.dir];s(e,r.line.width,r.line.color,r.fillcolor),e.style("opacity",o.selectedpoints&&!t.selected?.3:1)});else{s(c,l,o.line.color,o.fillcolor),r.selectAll("path.mean").style({"stroke-width":l,"stroke-dasharray":2*l+"px,"+l+"px"}).call(a.stroke,o.line.color);var u=r.selectAll("path.point");i.pointStyle(u,o,t)}})},styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace,a=r.selectAll("path.point");n.selectedpoints?i.selectedPointStyle(a,n):i.pointStyle(a,n,t)}}},{"../../components/color":45,"../../components/drawing":70,d3:10}],276:[function(t,e,r){"use strict";var n=t("../../lib").extendFlat,a=t("../ohlc/attributes"),i=t("../box/attributes");function o(t){return{line:{color:n({},i.line.color,{dflt:t}),width:i.line.width,editType:"style"},fillcolor:i.fillcolor,editType:"style"}}e.exports={x:a.x,open:a.open,high:a.high,low:a.low,close:a.close,line:{width:n({},i.line.width,{}),editType:"style"},increasing:o(a.increasing.line.color.dflt),decreasing:o(a.decreasing.line.color.dflt),text:a.text,whiskerwidth:n({},i.whiskerwidth,{dflt:0})}},{"../../lib":163,"../box/attributes":270,"../ohlc/attributes":292}],277:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../plots/cartesian/axes"),i=t("../ohlc/calc").calcCommon;function o(t,e,r,n){return{min:r,q1:Math.min(t,n),med:n,q3:Math.max(t,n),max:e}}e.exports=function(t,e){var r=t._fullLayout,l=a.getFromId(t,e.xaxis),s=a.getFromId(t,e.yaxis),c=l.makeCalcdata(e,"x"),u=i(t,e,c,s,o);return u.length?(n.extendFlat(u[0].t,{num:r._numBoxes,dPos:n.distinctVals(c).minDiff/2,posLetter:"x",valLetter:"y"}),r._numBoxes++,u):[{t:{empty:!0}}]}},{"../../lib":163,"../../plots/cartesian/axes":207,"../ohlc/calc":293}],278:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../components/color"),i=t("../ohlc/ohlc_defaults"),o=t("./attributes");function l(t,e,r,n){var i=r(n+".line.color");r(n+".line.width",e.line.width),r(n+".fillcolor",a.addOpacity(i,.5))}e.exports=function(t,e,r,a){function s(r,a){return n.coerce(t,e,o,r,a)}i(t,e,s,a)?(s("line.width"),l(t,e,s,"increasing"),l(t,e,s,"decreasing"),s("text"),s("whiskerwidth"),a._requestRangeslider[e.xaxis]=!0):e.visible=!1}},{"../../components/color":45,"../../lib":163,"../ohlc/ohlc_defaults":297,"./attributes":276}],279:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"candlestick",basePlotModule:t("../../plots/cartesian"),categories:["cartesian","svg","showLegend","candlestick","boxLayout"],meta:{},attributes:t("./attributes"),layoutAttributes:t("../box/layout_attributes"),supplyLayoutDefaults:t("../box/layout_defaults").supplyLayoutDefaults,setPositions:t("../box/set_positions").setPositions,supplyDefaults:t("./defaults"),calc:t("./calc"),plot:t("../box/plot").plot,layerName:"boxlayer",style:t("../box/style").style,hoverPoints:t("../ohlc/hover"),selectPoints:t("../ohlc/select")}},{"../../plots/cartesian":218,"../box/layout_attributes":271,"../box/layout_defaults":272,"../box/plot":273,"../box/set_positions":274,"../box/style":275,"../ohlc/hover":295,"../ohlc/select":299,"./attributes":276,"./calc":277,"./defaults":278}],280:[function(t,e,r){"use strict";var n=t("../bar/attributes");function a(t){var e={};e["autobin"+t]=!1;var r={};return r["^autobin"+t]=!1,{start:{valType:"any",dflt:null,editType:"calc",impliedEdits:r},end:{valType:"any",dflt:null,editType:"calc",impliedEdits:r},size:{valType:"any",dflt:null,editType:"calc",impliedEdits:r},editType:"calc",impliedEdits:e}}e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},text:n.text,orientation:n.orientation,histfunc:{valType:"enumerated",values:["count","sum","avg","min","max"],dflt:"count",editType:"calc"},histnorm:{valType:"enumerated",values:["","percent","probability","density","probability density"],dflt:"",editType:"calc"},cumulative:{enabled:{valType:"boolean",dflt:!1,editType:"calc"},direction:{valType:"enumerated",values:["increasing","decreasing"],dflt:"increasing",editType:"calc"},currentbin:{valType:"enumerated",values:["include","exclude","half"],dflt:"include",editType:"calc"},editType:"calc"},autobinx:{valType:"boolean",dflt:null,editType:"calc",impliedEdits:{"xbins.start":void 0,"xbins.end":void 0,"xbins.size":void 0}},nbinsx:{valType:"integer",min:0,dflt:0,editType:"calc"},xbins:a("x"),autobiny:{valType:"boolean",dflt:null,editType:"calc",impliedEdits:{"ybins.start":void 0,"ybins.end":void 0,"ybins.size":void 0}},nbinsy:{valType:"integer",min:0,dflt:0,editType:"calc"},ybins:a("y"),marker:n.marker,selected:n.selected,unselected:n.unselected,_deprecated:{bardir:n._deprecated.bardir}}},{"../bar/attributes":257}],281:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=t.length,n=0,a=0;a<r;a++)e[a]?(t[a]/=e[a],n+=t[a]):t[a]=null;return n}},{}],282:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){return r("histnorm"),n.forEach(function(t){r(t+"bins.start"),r(t+"bins.end"),r(t+"bins.size"),!1!==r("autobin"+t)&&r("nbins"+t)}),e}},{}],283:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports={count:function(t,e,r){return r[t]++,1},sum:function(t,e,r,a){var i=a[e];return n(i)?(i=Number(i),r[t]+=i,i):0},avg:function(t,e,r,a,i){var o=a[e];return n(o)&&(o=Number(o),r[t]+=o,i[t]++),0},min:function(t,e,r,a){var i=a[e];if(n(i)){if(i=Number(i),!n(r[t]))return r[t]=i,i;if(r[t]>i){var o=i-r[t];return r[t]=i,o}}return 0},max:function(t,e,r,a){var i=a[e];if(n(i)){if(i=Number(i),!n(r[t]))return r[t]=i,i;if(r[t]<i){var o=i-r[t];return r[t]=i,o}}return 0}}},{"fast-isnumeric":13}],284:[function(t,e,r){"use strict";var n=t("../../constants/numerical"),a=n.ONEAVGYEAR,i=n.ONEAVGMONTH,o=n.ONEDAY,l=n.ONEHOUR,s=n.ONEMIN,c=n.ONESEC,u=t("../../plots/cartesian/axes").tickIncrement;function f(t,e,r,n){if(t*e<=0)return 1/0;for(var a=Math.abs(e-t),i="date"===r.type,o=d(a,i),l=0;l<10;l++){var s=d(80*o,i);if(o===s)break;if(!p(s,t,e,i,r,n))break;o=s}return o}function d(t,e){return e&&t>c?t>o?t>1.1*a?a:t>1.1*i?i:o:t>l?l:t>s?s:c:Math.pow(10,Math.floor(Math.log(t)/Math.LN10))}function p(t,e,r,n,i,l){if(n&&t>o){var s=h(e,i,l),c=h(r,i,l),u=t===a?0:1;return s[u]!==c[u]}return Math.floor(r/t)-Math.floor(e/t)>.1}function h(t,e,r){var n=e.c2d(t,a,r).split("-");return""===n[0]&&(n.unshift(),n[0]="-"+n[0]),n}e.exports=function(t,e,r,n,i){var l,s,c=-1.1*e,d=-.1*e,p=t-d,h=r[0],g=r[1],y=Math.min(f(h+d,h+p,n,i),f(g+d,g+p,n,i)),v=Math.min(f(h+c,h+d,n,i),f(g+c,g+d,n,i));if(y>v&&v<Math.abs(g-h)/4e3?(l=y,s=!1):(l=Math.min(y,v),s=!0),"date"===n.type&&l>o){var m=l===a?1:6,x=l===a?"M12":"M1";return function(e,r){var o=n.c2d(e,a,i),l=o.indexOf("-",m);l>0&&(o=o.substr(0,l));var c=n.d2c(o,0,i);if(c<e){var f=u(c,x,!1,i);(c+f)/2<e+t&&(c=f)}return r&&s?u(c,x,!0,i):c}}return function(e,r){var n=l*Math.round(e/l);return n+l/10<e&&n+.9*l<e+t&&(n+=l),r&&s&&(n-=l),n}}},{"../../constants/numerical":145,"../../plots/cartesian/axes":207}],285:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib"),i=t("../../plots/cartesian/axes"),o=t("../bar/arrays_to_calcdata"),l=t("./bin_functions"),s=t("./norm_functions"),c=t("./average"),u=t("./clean_bins"),f=t("../../constants/numerical").ONEAVGMONTH,d=t("./bin_label_vals");function p(t,e,r,a,o){var l,s,c,u,f,d=a+"bins",p="overlay"===t._fullLayout.barmode;if(e._autoBinFinished)delete e._autoBinFinished;else{var v=p?[e]:g(t,e),m=[],x=1/0,b=1/0,_=-1/0,w="autobin"+a;for(l=0;l<v.length;l++){f=(s=v[l])._pos0=r.makeCalcdata(s,a);var k=s[d];if(s[w]||!k||null===k.start||null===k.end){c=s[a+"calendar"];var M=s.cumulative;if(k=i.autoBin(f,r,s["nbins"+a],!1,c),p&&0===k._dataSpan&&"category"!==r.type){if(o)return[k,f,!0];k=h(t,e,r,a,d)}M.enabled&&"include"!==M.currentbin&&("decreasing"===M.direction?b=Math.min(b,r.r2c(k.start,0,c)-k.size):_=Math.max(_,r.r2c(k.end,0,c)+k.size)),m.push(s)}else u||(u={size:k.size,start:r.r2c(k.start,0,c),end:r.r2c(k.end,0,c)});x=y(x,k.size),b=Math.min(b,r.r2c(k.start,0,c)),_=Math.max(_,r.r2c(k.end,0,c)),l&&(s._autoBinFinished=1)}if(u&&n(u.size)&&n(x)){x=x>u.size/1.9?u.size:u.size/Math.ceil(u.size/x);var T=u.start+(u.size-x)/2;b=T-x*Math.ceil((T-b)/x)}for(l=0;l<m.length;l++)c=(s=m[l])[a+"calendar"],s._input[d]=s[d]={start:r.c2r(b,0,c),end:r.c2r(_,0,c),size:x},s._input[w]=s[w]}return f=e._pos0,delete e._pos0,[e[d],f]}function h(t,e,r,n,i){var o,l,s=g(t,e),c=!1,u=1/0,f=[e];for(o=0;o<s.length;o++)if((l=s[o])===e)c=!0;else if(c){var d=p(t,l,r,n,!0),h=d[0],y=d[2];l._autoBinFinished=1,l._pos0=d[1],y?f.push(l):u=Math.min(u,h.size)}else u=Math.min(u,l[i].size);var v=new Array(f.length);for(o=0;o<f.length;o++)for(var m=f[o]._pos0,x=0;x<m.length;x++)if(void 0!==m[x]){v[o]=m[x];break}for(isFinite(u)||(u=a.distinctVals(v).minDiff),o=0;o<f.length;o++){var b=(l=f[o])[n+"calendar"];l._input[i]=l[i]={start:r.c2r(v[o]-u/2,0,b),end:r.c2r(v[o]+u/2,0,b),size:u}}return e[i]}function g(t,e){for(var r=e.xaxis,n=e.yaxis,a=e.orientation,i=[],o=t._fullData,l=0;l<o.length;l++){var s=o[l];"histogram"===s.type&&!0===s.visible&&s.orientation===a&&s.xaxis===r&&s.yaxis===n&&i.push(s)}return i}function y(t,e){if(t===1/0)return e;var r=v(t);return v(e)<r?e:t}function v(t){return n(t)?t:"string"==typeof t&&"M"===t.charAt(0)?f*+t.substr(1):1/0}e.exports=function(t,e){if(!0===e.visible){var r,f=[],h=[],g=i.getFromId(t,"h"===e.orientation?e.yaxis||"y":e.xaxis||"x"),y="h"===e.orientation?"y":"x",v={x:"y",y:"x"}[y],m=e[y+"calendar"],x=e.cumulative;u(e,g,y);var b,_,w,k=p(t,e,g,y),M=k[0],T=k[1],A="string"==typeof M.size,L=[],C=A?L:M,S=[],O=[],P=[],D=0,z=e.histnorm,E=e.histfunc,I=-1!==z.indexOf("density");x.enabled&&I&&(z=z.replace(/ ?density$/,""),I=!1);var N,R="max"===E||"min"===E?null:0,F=l.count,j=s[z],B=!1,H=function(t){return g.r2c(t,0,m)};for(a.isArrayOrTypedArray(e[v])&&"count"!==E&&(N=e[v],B="avg"===E,F=l[E]),r=H(M.start),_=H(M.end)+(r-i.tickIncrement(r,M.size,!1,m))/1e6;r<_&&f.length<1e6&&(b=i.tickIncrement(r,M.size,!1,m),f.push((r+b)/2),h.push(R),P.push([]),L.push(r),I&&S.push(1/(b-r)),B&&O.push(0),!(b<=r));)r=b;L.push(r),A||"date"!==g.type||(C={start:H(C.start),end:H(C.end),size:C.size});var q,V=h.length,U=!0,G=1/0,Y=1/0,X={};for(r=0;r<T.length;r++){var Z=T[r];(w=a.findBin(Z,C))>=0&&w<V&&(D+=F(w,r,h,N,O),U&&P[w].length&&Z!==T[P[w][0]]&&(U=!1),P[w].push(r),X[r]=w,G=Math.min(G,Z-L[w]),Y=Math.min(Y,L[w+1]-Z))}U||(q=d(G,Y,L,g,m)),B&&(D=c(h,O)),j&&j(h,D,S),x.enabled&&function(t,e,r){var n,a,i;function o(e){i=t[e],t[e]/=2}function l(e){a=t[e],t[e]=i+a/2,i+=a}if("half"===r)if("increasing"===e)for(o(0),n=1;n<t.length;n++)l(n);else for(o(t.length-1),n=t.length-2;n>=0;n--)l(n);else if("increasing"===e){for(n=1;n<t.length;n++)t[n]+=t[n-1];"exclude"===r&&(t.unshift(0),t.pop())}else{for(n=t.length-2;n>=0;n--)t[n]+=t[n+1];"exclude"===r&&(t.push(0),t.shift())}}(h,x.direction,x.currentbin);var W=Math.min(f.length,h.length),Q=[],J=0,$=W-1;for(r=0;r<W;r++)if(h[r]){J=r;break}for(r=W-1;r>=J;r--)if(h[r]){$=r;break}for(r=J;r<=$;r++)if(n(f[r])&&n(h[r])){var K={p:f[r],s:h[r],b:0};x.enabled||(K.pts=P[r],U?K.p0=K.p1=P[r].length?T[P[r][0]]:f[r]:(K.p0=q(L[r]),K.p1=q(L[r+1],!0))),Q.push(K)}return 1===Q.length&&(Q[0].width1=i.tickIncrement(Q[0].p,M.size,!1,m)-Q[0].p),o(Q,e),a.isArrayOrTypedArray(e.selectedpoints)&&a.tagSelected(Q,e,X),Q}}},{"../../constants/numerical":145,"../../lib":163,"../../plots/cartesian/axes":207,"../bar/arrays_to_calcdata":256,"./average":281,"./bin_functions":283,"./bin_label_vals":284,"./clean_bins":286,"./norm_functions":291,"fast-isnumeric":13}],286:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib").cleanDate,i=t("../../constants/numerical"),o=i.ONEDAY,l=i.BADNUM;e.exports=function(t,e,r){var i=e.type,s=r+"bins",c=t[s];c||(c=t[s]={});var u="date"===i?function(t){return t||0===t?a(t,l,c.calendar):null}:function(t){return n(t)?Number(t):null};c.start=u(c.start),c.end=u(c.end);var f="date"===i?o:1,d=c.size;if(n(d))c.size=d>0?Number(d):f;else if("string"!=typeof d)c.size=f;else{var p=d.charAt(0),h=d.substr(1);((h=n(h)?Number(h):0)<=0||"date"!==i||"M"!==p||h!==Math.round(h))&&(c.size=f)}var g="autobin"+r;"boolean"!=typeof t[g]&&(t[g]=t._fullInput[g]=t._input[g]=!((c.start||0===c.start)&&(c.end||0===c.end))),t[g]||(delete t["nbins"+r],delete t._fullInput["nbins"+r])}},{"../../constants/numerical":145,"../../lib":163,"fast-isnumeric":13}],287:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../lib"),i=t("../../components/color"),o=t("./bin_defaults"),l=t("../bar/style_defaults"),s=t("./attributes");e.exports=function(t,e,r,c){function u(r,n){return a.coerce(t,e,s,r,n)}var f=u("x"),d=u("y");u("cumulative.enabled")&&(u("cumulative.direction"),u("cumulative.currentbin")),u("text");var p=u("orientation",d&&!f?"h":"v"),h="v"===p?"x":"y",g="v"===p?"y":"x",y=f&&d?Math.min(f.length&&d.length):(e[h]||[]).length;if(y){e._length=y,n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],c),e[g]&&u("histfunc"),o(t,e,u,[h]),l(t,e,u,r,c);var v=n.getComponentMethod("errorbars","supplyDefaults");v(t,e,i.defaultLine,{axis:"y"}),v(t,e,i.defaultLine,{axis:"x",inherit:"y"}),a.coerceSelectionMarkerOpacity(e,u)}else e.visible=!1}},{"../../components/color":45,"../../lib":163,"../../registry":247,"../bar/style_defaults":269,"./attributes":280,"./bin_defaults":282}],288:[function(t,e,r){"use strict";e.exports=function(t,e,r,n,a){if(t.x="xVal"in e?e.xVal:e.x,t.y="yVal"in e?e.yVal:e.y,e.xa&&(t.xaxis=e.xa),e.ya&&(t.yaxis=e.ya),!(r.cumulative||{}).enabled){var i,o=Array.isArray(a)?n[0].pts[a[0]][a[1]]:n[a].pts;if(t.pointNumbers=o,t.binNumber=t.pointNumber,delete t.pointNumber,delete t.pointIndex,r._indexToPoints){i=[];for(var l=0;l<o.length;l++)i=i.concat(r._indexToPoints[o[l]])}else i=o;t.pointIndices=i}return t}},{}],289:[function(t,e,r){"use strict";var n=t("../bar/hover"),a=t("../../plots/cartesian/axes").hoverLabelText;e.exports=function(t,e,r,i){var o=n(t,e,r,i);if(o){var l=(t=o[0]).cd[t.index],s=t.cd[0].trace;if(!s.cumulative.enabled){var c="h"===s.orientation?"y":"x";t[c+"Label"]=a(t[c+"a"],l.p0,l.p1)}return o}}},{"../../plots/cartesian/axes":207,"../bar/hover":260}],290:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("../bar/layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("../bar/layout_defaults"),n.calc=t("./calc"),n.setPositions=t("../bar/set_positions"),n.plot=t("../bar/plot"),n.layerName="barlayer",n.style=t("../bar/style").style,n.styleOnSelect=t("../bar/style").styleOnSelect,n.colorbar=t("../scatter/marker_colorbar"),n.hoverPoints=t("./hover"),n.selectPoints=t("../bar/select"),n.eventData=t("./event_data"),n.moduleType="trace",n.name="histogram",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","bar","histogram","oriented","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":218,"../bar/layout_attributes":262,"../bar/layout_defaults":263,"../bar/plot":264,"../bar/select":265,"../bar/set_positions":266,"../bar/style":268,"../scatter/marker_colorbar":331,"./attributes":280,"./calc":285,"./defaults":287,"./event_data":288,"./hover":289}],291:[function(t,e,r){"use strict";e.exports={percent:function(t,e){for(var r=t.length,n=100/e,a=0;a<r;a++)t[a]*=n},probability:function(t,e){for(var r=t.length,n=0;n<r;n++)t[n]/=e},density:function(t,e,r,n){var a=t.length;n=n||1;for(var i=0;i<a;i++)t[i]*=r[i]*n},"probability density":function(t,e,r,n){var a=t.length;n&&(e/=n);for(var i=0;i<a;i++)t[i]*=r[i]/e}}},{}],292:[function(t,e,r){"use strict";var n=t("../../lib").extendFlat,a=t("../scatter/attributes"),i=t("../../components/drawing/attributes").dash,o=a.line;function l(t){return{line:{color:n({},o.color,{dflt:t}),width:o.width,dash:i,editType:"style"},editType:"style"}}e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes"},open:{valType:"data_array",editType:"calc"},high:{valType:"data_array",editType:"calc"},low:{valType:"data_array",editType:"calc"},close:{valType:"data_array",editType:"calc"},line:{width:n({},o.width,{}),dash:n({},i,{}),editType:"style"},increasing:l("#3D9970"),decreasing:l("#FF4136"),text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},tickwidth:{valType:"number",min:0,max:.5,dflt:.3,editType:"calcIfAutorange"}}},{"../../components/drawing/attributes":69,"../../lib":163,"../scatter/attributes":314}],293:[function(t,e,r){"use strict";var n=t("../../lib"),a=n._,i=t("../../plots/cartesian/axes"),o=t("../../constants/numerical").BADNUM;function l(t,e,r,n){return{o:t,h:e,l:r,c:n}}function s(t,e,r,n,l){for(var s=n.makeCalcdata(e,"open"),c=n.makeCalcdata(e,"high"),u=n.makeCalcdata(e,"low"),f=n.makeCalcdata(e,"close"),d=Array.isArray(e.text),p=!0,h=null,g=[],y=0;y<r.length;y++){var v=r[y],m=s[y],x=c[y],b=u[y],_=f[y];if(v!==o&&m!==o&&x!==o&&b!==o&&_!==o){_===m?null!==h&&_!==h&&(p=_>h):p=_>m,h=_;var w=l(m,x,b,_);w.pos=v,w.yc=(m+_)/2,w.i=y,w.dir=p?"increasing":"decreasing",d&&(w.tx=e.text[y]),g.push(w)}}return i.expand(n,u.concat(c),{padded:!0}),g.length&&(g[0].t={labels:{open:a(t,"open:")+" ",high:a(t,"high:")+" ",low:a(t,"low:")+" ",close:a(t,"close:")+" "}}),g}e.exports={calc:function(t,e){var r=i.getFromId(t,e.xaxis),a=i.getFromId(t,e.yaxis),o=function(t,e,r){var a=r._minDiff;if(!a){var i,o=t._fullData,l=[];for(a=1/0,i=0;i<o.length;i++){var s=o[i];if("ohlc"===s.type&&!0===s.visible&&s.xaxis===e._id){l.push(s);var c=e.makeCalcdata(s,"x");s._xcalc=c;var u=n.distinctVals(c).minDiff;u&&isFinite(u)&&(a=Math.min(a,u))}}for(a===1/0&&(a=1),i=0;i<l.length;i++)l[i]._minDiff=a}return a*r.tickwidth}(t,r,e),c=e._minDiff;e._minDiff=null;var u=e._xcalc;e._xcalc=null;var f=s(t,e,u,a,l);return i.expand(r,u,{vpad:c/2}),f.length?(n.extendFlat(f[0].t,{wHover:c/2,tickLen:o}),f):[{t:{empty:!0}}]},calcCommon:s}},{"../../constants/numerical":145,"../../lib":163,"../../plots/cartesian/axes":207}],294:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./ohlc_defaults"),i=t("./attributes");function o(t,e,r,n){r(n+".line.color"),r(n+".line.width",e.line.width),r(n+".line.dash",e.line.dash)}e.exports=function(t,e,r,l){function s(r,a){return n.coerce(t,e,i,r,a)}a(t,e,s,l)?(s("line.width"),s("line.dash"),o(t,e,s,"increasing"),o(t,e,s,"decreasing"),s("text"),s("tickwidth"),l._requestRangeslider[e.xaxis]=!0):e.visible=!1}},{"../../lib":163,"./attributes":292,"./ohlc_defaults":297}],295:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),a=t("../../components/fx"),i=t("../../components/color"),o=t("../scatter/fill_hover_text"),l={increasing:"\u25b2",decreasing:"\u25bc"};e.exports=function(t,e,r,s){var c=t.cd,u=t.xa,f=t.ya,d=c[0].trace,p=c[0].t,h=d.type,g="ohlc"===h?"l":"min",y="ohlc"===h?"h":"max",v=p.bPos||0,m=e-v,x=p.bdPos||p.tickLen,b=p.wHover,_=Math.min(1,x/Math.abs(u.r2c(u.range[1])-u.r2c(u.range[0]))),w=t.maxHoverDistance-_,k=t.maxSpikeDistance-_;function M(t){var e=t.pos-m;return a.inbox(e-b,e+b,w)}function T(t){return a.inbox(t[g]-r,t[y]-r,w)}function A(t){return(M(t)+T(t))/2}var L=a.getDistanceFunction(s,M,T,A);if(a.getClosest(c,L,t),!1===t.index)return[];var C=c[t.index],S=t.index=C.i,O=C.dir,P=d[O],D=P.line.color;function z(t){return p.labels[t]+n.hoverLabelText(f,d[t][S])}i.opacity(D)&&P.line.width?t.color=D:t.color=P.fillcolor,t.x0=u.c2p(C.pos+v-x,!0),t.x1=u.c2p(C.pos+v+x,!0),t.xLabelVal=C.pos,t.spikeDistance=A(C)*k/w,t.xSpike=u.c2p(C.pos,!0);var E=d.hoverinfo,I=E.split("+"),N="all"===E,R=N||-1!==I.indexOf("y"),F=N||-1!==I.indexOf("text"),j=R?[z("open"),z("high"),z("low"),z("close")+" "+l[O]]:[];return F&&o(C,d,j),t.extraText=j.join("<br>"),t.y0=t.y1=f.c2p(C.yc,!0),[t]}},{"../../components/color":45,"../../components/fx":87,"../../plots/cartesian/axes":207,"../scatter/fill_hover_text":321}],296:[function(t,e,r){"use strict";e.exports={moduleType:"trace",name:"ohlc",basePlotModule:t("../../plots/cartesian"),categories:["cartesian","svg","showLegend"],meta:{},attributes:t("./attributes"),supplyDefaults:t("./defaults"),calc:t("./calc").calc,plot:t("./plot"),style:t("./style"),hoverPoints:t("./hover"),selectPoints:t("./select")}},{"../../plots/cartesian":218,"./attributes":292,"./calc":293,"./defaults":294,"./hover":295,"./plot":298,"./select":299,"./style":300}],297:[function(t,e,r){"use strict";var n=t("../../registry");e.exports=function(t,e,r,a){var i=r("x"),o=r("open"),l=r("high"),s=r("low"),c=r("close");if(n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x"],a),o&&l&&s&&c){var u=Math.min(o.length,l.length,s.length,c.length);return i&&(u=Math.min(u,i.length)),e._length=u,u}}},{"../../registry":247}],298:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../lib");e.exports=function(t,e,r,i){var o=e.xaxis,l=e.yaxis,s=i.selectAll("g.trace").data(r,function(t){return t[0].trace.uid});s.enter().append("g").attr("class","trace ohlc"),s.exit().remove(),s.order(),s.each(function(t){var r=t[0],i=r.t,s=r.trace,c=n.select(this);if(e.isRangePlot||(r.node3=c),!0!==s.visible||i.empty)c.remove();else{var u=i.tickLen,f=c.selectAll("path").data(a.identity);f.enter().append("path"),f.exit().remove(),f.attr("d",function(t){var e=o.c2p(t.pos,!0),r=o.c2p(t.pos-u,!0),n=o.c2p(t.pos+u,!0);return"M"+r+","+l.c2p(t.o,!0)+"H"+e+"M"+e+","+l.c2p(t.h,!0)+"V"+l.c2p(t.l,!0)+"M"+n+","+l.c2p(t.c,!0)+"H"+e})}})}},{"../../lib":163,d3:10}],299:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n=t.cd,a=t.xaxis,i=t.yaxis,o=[],l=n[0].t.bPos||0;if(!1===e)for(r=0;r<n.length;r++)n[r].selected=0;else for(r=0;r<n.length;r++){var s=n[r];e.contains([a.c2p(s.pos+l),i.c2p(s.yc)])?(o.push({pointNumber:s.i,x:a.c2d(s.pos),y:i.c2d(s.yc)}),s.selected=1):s.selected=0}return o}},{}],300:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/drawing"),i=t("../../components/color");e.exports=function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.ohlclayer").selectAll("g.trace");r.style("opacity",function(t){return t[0].trace.opacity}),r.each(function(t){var e=t[0].trace;n.select(this).selectAll("path").each(function(t){var r=e[t.dir].line;n.select(this).style("fill","none").call(i.stroke,r.color).call(a.dashLine,r.dash,r.width).style("opacity",e.selectedpoints&&!t.selected?.3:1)})})}},{"../../components/color":45,"../../components/drawing":70,d3:10}],301:[function(t,e,r){"use strict";var n=t("../../components/color/attributes"),a=t("../../plots/font_attributes"),i=t("../../plots/attributes"),o=t("../../plots/domain").attributes,l=t("../../lib/extend").extendFlat,s=a({editType:"calc",colorEditType:"style"});e.exports={labels:{valType:"data_array",editType:"calc"},label0:{valType:"number",dflt:0,editType:"calc"},dlabel:{valType:"number",dflt:1,editType:"calc"},values:{valType:"data_array",editType:"calc"},marker:{colors:{valType:"data_array",editType:"calc"},line:{color:{valType:"color",dflt:n.defaultLine,arrayOk:!0,editType:"style"},width:{valType:"number",min:0,dflt:0,arrayOk:!0,editType:"style"},editType:"calc"},editType:"calc"},text:{valType:"data_array",editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},scalegroup:{valType:"string",dflt:"",editType:"calc"},textinfo:{valType:"flaglist",flags:["label","text","value","percent"],extras:["none"],editType:"calc"},hoverinfo:l({},i.hoverinfo,{flags:["label","text","value","percent","name"]}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"auto",arrayOk:!0,editType:"calc"},textfont:l({},s,{}),insidetextfont:l({},s,{}),outsidetextfont:l({},s,{}),domain:o({name:"pie",trace:!0,editType:"calc"}),hole:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},sort:{valType:"boolean",dflt:!0,editType:"calc"},direction:{valType:"enumerated",values:["clockwise","counterclockwise"],dflt:"counterclockwise",editType:"calc"},rotation:{valType:"number",min:-360,max:360,dflt:0,editType:"calc"},pull:{valType:"number",min:0,max:1,dflt:0,arrayOk:!0,editType:"calc"}}},{"../../components/color/attributes":44,"../../lib/extend":157,"../../plots/attributes":204,"../../plots/domain":232,"../../plots/font_attributes":233}],302:[function(t,e,r){"use strict";var n=t("../../registry"),a=t("../../plots/get_data").getModuleCalcData;r.name="pie",r.plot=function(t){var e=n.getModule("pie"),r=a(t.calcdata,e)[0];r.length&&e.plot(t,r)},r.clean=function(t,e,r,n){var a=n._has&&n._has("pie"),i=e._has&&e._has("pie");a&&!i&&n._pielayer.selectAll("g.trace").remove()}},{"../../plots/get_data":235,"../../registry":247}],303:[function(t,e,r){"use strict";var n,a=t("fast-isnumeric"),i=t("../../lib").isArrayOrTypedArray,o=t("tinycolor2"),l=t("../../components/color"),s=t("./helpers");function c(t,e){if(!n){var r=l.defaults;n=u(r)}var a=e||n;return a[t%a.length]}function u(t){var e,r=t.slice();for(e=0;e<t.length;e++)r.push(o(t[e]).lighten(20).toHexString());for(e=0;e<t.length;e++)r.push(o(t[e]).darken(20).toHexString());return r}e.exports=function(t,e){var r,n,f,d,p,h=e.values,g=i(h)&&h.length,y=e.labels,v=e.marker.colors||[],m=[],x=t._fullLayout,b=x.colorway,_=x._piecolormap,w={},k=0,M=x.hiddenlabels||[];if(x._piecolorway||b===l.defaults||(x._piecolorway=u(b)),e.dlabel)for(y=new Array(h.length),r=0;r<h.length;r++)y[r]=String(e.label0+r*e.dlabel);function T(t,e){return!!t&&(!!(t=o(t)).isValid()&&(t=l.addOpacity(t,t.getAlpha()),_[e]||(_[e]=t),t))}var A=(g?h:y).length;for(r=0;r<A;r++){if(g){if(n=h[r],!a(n))continue;if((n=+n)<0)continue}else n=1;void 0!==(f=y[r])&&""!==f||(f=r);var L=w[f=String(f)];void 0===L?(w[f]=m.length,(d=-1!==M.indexOf(f))||(k+=n),m.push({v:n,label:f,color:T(v[r]),i:r,pts:[r],hidden:d})):((p=m[L]).v+=n,p.pts.push(r),p.hidden||(k+=n),!1===p.color&&v[r]&&(p.color=T(v[r],f)))}for(e.sort&&m.sort(function(t,e){return e.v-t.v}),r=0;r<m.length;r++)!1===(p=m[r]).color&&(_[p.label]?p.color=_[p.label]:(_[p.label]=p.color=c(x._piedefaultcolorcount,x._piecolorway),x._piedefaultcolorcount++));if(m[0]&&(m[0].vTotal=k),e.textinfo&&"none"!==e.textinfo){var C,S=-1!==e.textinfo.indexOf("label"),O=-1!==e.textinfo.indexOf("text"),P=-1!==e.textinfo.indexOf("value"),D=-1!==e.textinfo.indexOf("percent"),z=x.separators;for(r=0;r<m.length;r++){if(p=m[r],C=S?[p.label]:[],O){var E=s.getFirstFilled(e.text,p.pts);E&&C.push(E)}P&&C.push(s.formatPieValue(p.v,z)),D&&C.push(s.formatPiePercent(p.v/k,z)),p.text=C.join("<br>")}}return m}},{"../../components/color":45,"../../lib":163,"./helpers":306,"fast-isnumeric":13,tinycolor2:28}],304:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./attributes"),i=t("../../plots/domain").defaults;e.exports=function(t,e,r,o){function l(r,i){return n.coerce(t,e,a,r,i)}var s,c=n.coerceFont,u=l("values"),f=n.isArrayOrTypedArray(u),d=l("labels");if(Array.isArray(d)?(s=d.length,f&&(s=Math.min(s,u.length))):f&&(s=u.length,l("label0"),l("dlabel")),s){e._length=s,l("marker.line.width")&&l("marker.line.color"),l("marker.colors"),l("scalegroup");var p=l("text"),h=l("textinfo",Array.isArray(p)?"text+percent":"percent");if(l("hovertext"),h&&"none"!==h){var g=l("textposition"),y=Array.isArray(g)||"auto"===g,v=y||"inside"===g,m=y||"outside"===g;if(v||m){var x=c(l,"textfont",o.font);v&&c(l,"insidetextfont",x),m&&c(l,"outsidetextfont",x)}}i(e,o,l),l("hole"),l("sort"),l("direction"),l("rotation"),l("pull")}else e.visible=!1}},{"../../lib":163,"../../plots/domain":232,"./attributes":301}],305:[function(t,e,r){"use strict";var n=t("../../components/fx/helpers").appendArrayMultiPointValues;e.exports=function(t,e){var r={curveNumber:e.index,pointNumbers:t.pts,data:e._input,fullData:e,label:t.label,color:t.color,value:t.v,v:t.v};return 1===t.pts.length&&(r.pointNumber=r.i=t.pts[0]),n(r,e,t.pts),r}},{"../../components/fx/helpers":84}],306:[function(t,e,r){"use strict";var n=t("../../lib");r.formatPiePercent=function(t,e){var r=(100*t).toPrecision(3);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)+"%"},r.formatPieValue=function(t,e){var r=t.toPrecision(10);return-1!==r.lastIndexOf(".")&&(r=r.replace(/[.]?0+$/,"")),n.numSeparate(r,e)},r.getFirstFilled=function(t,e){if(Array.isArray(t))for(var r=0;r<e.length;r++){var n=t[e[r]];if(n||0===n)return n}},r.castOption=function(t,e){return Array.isArray(t)?r.getFirstFilled(t,e):t||void 0}},{"../../lib":163}],307:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.layoutAttributes=t("./layout_attributes"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.styleOne=t("./style_one"),n.moduleType="trace",n.name="pie",n.basePlotModule=t("./base_plot"),n.categories=["pie","showLegend"],n.meta={},e.exports=n},{"./attributes":301,"./base_plot":302,"./calc":303,"./defaults":304,"./layout_attributes":308,"./layout_defaults":309,"./plot":310,"./style":311,"./style_one":312}],308:[function(t,e,r){"use strict";e.exports={hiddenlabels:{valType:"data_array",editType:"calc"}}},{}],309:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("./layout_attributes");e.exports=function(t,e){var r,i;r="hiddenlabels",n.coerce(t,e,a,r,i)}},{"../../lib":163,"./layout_attributes":308}],310:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/fx"),i=t("../../components/color"),o=t("../../components/drawing"),l=t("../../lib"),s=t("../../lib/svg_text_utils"),c=t("./helpers"),u=t("./event_data");function f(t,e){if(t.v===e.vTotal&&!e.trace.hole)return 1;var r=Math.PI*Math.min(t.v/e.vTotal,.5);return Math.min(1/(1+1/Math.sin(r)),(1-e.trace.hole)/2)}function d(t,e){var r=e.pxmid[0],n=e.pxmid[1],a=t.width/2,i=t.height/2;return r<0&&(a*=-1),n<0&&(i*=-1),{scale:1,rCenter:1,rotate:0,x:a+Math.abs(i)*(a>0?1:-1)/2,y:i/(1+r*r/(n*n)),outside:!0}}e.exports=function(t,e){var r=t._fullLayout;!function(t,e){var r,n,a,i,o,l,s,c,u,f=[];for(a=0;a<t.length;a++){if(o=t[a][0],l=o.trace,r=e.w*(l.domain.x[1]-l.domain.x[0]),n=e.h*(l.domain.y[1]-l.domain.y[0]),s=l.pull,Array.isArray(s))for(s=0,i=0;i<l.pull.length;i++)l.pull[i]>s&&(s=l.pull[i]);o.r=Math.min(r,n)/(2+2*s),o.cx=e.l+e.w*(l.domain.x[1]+l.domain.x[0])/2,o.cy=e.t+e.h*(2-l.domain.y[1]-l.domain.y[0])/2,l.scalegroup&&-1===f.indexOf(l.scalegroup)&&f.push(l.scalegroup)}for(i=0;i<f.length;i++){for(u=1/0,c=f[i],a=0;a<t.length;a++)(o=t[a][0]).trace.scalegroup===c&&(u=Math.min(u,o.r*o.r/o.vTotal));for(a=0;a<t.length;a++)(o=t[a][0]).trace.scalegroup===c&&(o.r=Math.sqrt(u*o.vTotal))}}(e,r._size);var p=r._pielayer.selectAll("g.trace").data(e);p.enter().append("g").attr({"stroke-linejoin":"round",class:"trace"}),p.exit().remove(),p.order(),p.each(function(e){var p=n.select(this),h=e[0],g=h.trace;!function(t){var e,r,n,a=t[0],i=a.trace,o=i.rotation*Math.PI/180,l=2*Math.PI/a.vTotal,s="px0",c="px1";if("counterclockwise"===i.direction){for(e=0;e<t.length&&t[e].hidden;e++);if(e===t.length)return;o+=l*t[e].v,l*=-1,s="px1",c="px0"}function u(t){return[a.r*Math.sin(t),-a.r*Math.cos(t)]}for(n=u(o),e=0;e<t.length;e++)(r=t[e]).hidden||(r[s]=n,o+=l*r.v/2,r.pxmid=u(o),r.midangle=o,o+=l*r.v/2,n=u(o),r[c]=n,r.largeArc=r.v>a.vTotal/2?1:0)}(e),p.each(function(){var p=n.select(this).selectAll("g.slice").data(e);p.enter().append("g").classed("slice",!0),p.exit().remove();var y=[[[],[]],[[],[]]],v=!1;p.each(function(e){if(e.hidden)n.select(this).selectAll("path,g").remove();else{e.pointNumber=e.i,e.curveNumber=g.index,y[e.pxmid[1]<0?0:1][e.pxmid[0]<0?0:1].push(e);var i=h.cx,p=h.cy,m=n.select(this),x=m.selectAll("path.surface").data([e]),b=!1,_=!1;if(x.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),m.select("path.textline").remove(),m.on("mouseover",function(){var o=t._fullLayout,l=t._fullData[g.index];if(!t._dragging&&!1!==o.hovermode){var s=l.hoverinfo;if(Array.isArray(s)&&(s=a.castHoverinfo({hoverinfo:[c.castOption(s,e.pts)],_module:g._module},o,0)),"all"===s&&(s="label+text+value+percent+name"),"none"!==s&&"skip"!==s&&s){var d=f(e,h),y=i+e.pxmid[0]*(1-d),v=p+e.pxmid[1]*(1-d),m=r.separators,x=[];if(-1!==s.indexOf("label")&&x.push(e.label),-1!==s.indexOf("text")){var w=c.castOption(l.hovertext||l.text,e.pts);w&&x.push(w)}-1!==s.indexOf("value")&&x.push(c.formatPieValue(e.v,m)),-1!==s.indexOf("percent")&&x.push(c.formatPiePercent(e.v/h.vTotal,m));var k=g.hoverlabel,M=k.font;a.loneHover({x0:y-d*h.r,x1:y+d*h.r,y:v,text:x.join("<br>"),name:-1!==s.indexOf("name")?l.name:void 0,idealAlign:e.pxmid[0]<0?"left":"right",color:c.castOption(k.bgcolor,e.pts)||e.color,borderColor:c.castOption(k.bordercolor,e.pts),fontFamily:c.castOption(M.family,e.pts),fontSize:c.castOption(M.size,e.pts),fontColor:c.castOption(M.color,e.pts)},{container:o._hoverlayer.node(),outerContainer:o._paper.node(),gd:t}),b=!0}t.emit("plotly_hover",{points:[u(e,l)],event:n.event}),_=!0}}).on("mouseout",function(r){var i=t._fullLayout,o=t._fullData[g.index];_&&(r.originalEvent=n.event,t.emit("plotly_unhover",{points:[u(e,o)],event:n.event}),_=!1),b&&(a.loneUnhover(i._hoverlayer.node()),b=!1)}).on("click",function(){var r=t._fullLayout,i=t._fullData[g.index];t._dragging||!1===r.hovermode||(t._hoverdata=[u(e,i)],a.click(t,n.event))}),g.pull){var w=+c.castOption(g.pull,e.pts)||0;w>0&&(i+=w*e.pxmid[0],p+=w*e.pxmid[1])}e.cxFinal=i,e.cyFinal=p;var k=g.hole;if(e.v===h.vTotal){var M="M"+(i+e.px0[0])+","+(p+e.px0[1])+S(e.px0,e.pxmid,!0,1)+S(e.pxmid,e.px0,!0,1)+"Z";k?x.attr("d","M"+(i+k*e.px0[0])+","+(p+k*e.px0[1])+S(e.px0,e.pxmid,!1,k)+S(e.pxmid,e.px0,!1,k)+"Z"+M):x.attr("d",M)}else{var T=S(e.px0,e.px1,!0,1);if(k){var A=1-k;x.attr("d","M"+(i+k*e.px1[0])+","+(p+k*e.px1[1])+S(e.px1,e.px0,!1,k)+"l"+A*e.px0[0]+","+A*e.px0[1]+T+"Z")}else x.attr("d","M"+i+","+p+"l"+e.px0[0]+","+e.px0[1]+T+"Z")}var L=c.castOption(g.textposition,e.pts),C=m.selectAll("g.slicetext").data(e.text&&"none"!==L?[0]:[]);C.enter().append("g").classed("slicetext",!0),C.exit().remove(),C.each(function(){var r=l.ensureSingle(n.select(this),"text","",function(t){t.attr("data-notex",1)});r.text(e.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(o.font,"outside"===L?g.outsidetextfont:g.insidetextfont).call(s.convertToTspans,t);var a,c=o.bBox(r.node());"outside"===L?a=d(c,e):(a=function(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),a=t.width/t.height,i=Math.PI*Math.min(e.v/r.vTotal,.5),o=1-r.trace.hole,l=f(e,r),s={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(s.scale>=1)return s;var c=a+1/(2*Math.tan(i)),u=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),o/(Math.sqrt(a*a+o/2)+a)),d={scale:2*u/t.height,rCenter:Math.cos(u/r.r)-u*a/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},p=1/a,h=p+1/(2*Math.tan(i)),g=r.r*Math.min(1/(Math.sqrt(h*h+.5)+h),o/(Math.sqrt(p*p+o/2)+p)),y={scale:2*g/t.width,rCenter:Math.cos(g/r.r)-g/a/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},v=y.scale>d.scale?y:d;return s.scale<1&&v.scale>s.scale?v:s}(c,e,h),"auto"===L&&a.scale<1&&(r.call(o.font,g.outsidetextfont),g.outsidetextfont.family===g.insidetextfont.family&&g.outsidetextfont.size===g.insidetextfont.size||(c=o.bBox(r.node())),a=d(c,e)));var u=i+e.pxmid[0]*a.rCenter+(a.x||0),y=p+e.pxmid[1]*a.rCenter+(a.y||0);a.outside&&(e.yLabelMin=y-c.height/2,e.yLabelMid=y,e.yLabelMax=y+c.height/2,e.labelExtraX=0,e.labelExtraY=0,v=!0),r.attr("transform","translate("+u+","+y+")"+(a.scale<1?"scale("+a.scale+")":"")+(a.rotate?"rotate("+a.rotate+")":"")+"translate("+-(c.left+c.right)/2+","+-(c.top+c.bottom)/2+")")})}function S(t,r,n,a){return"a"+a*h.r+","+a*h.r+" 0 "+e.largeArc+(n?" 1 ":" 0 ")+a*(r[0]-t[0])+","+a*(r[1]-t[1])}}),v&&function(t,e){var r,n,a,i,o,l,s,u,f,d,p,h,g;function y(t,e){return t.pxmid[1]-e.pxmid[1]}function v(t,e){return e.pxmid[1]-t.pxmid[1]}function m(t,r){r||(r={});var a,u,f,p,h,g,y=r.labelExtraY+(n?r.yLabelMax:r.yLabelMin),v=n?t.yLabelMin:t.yLabelMax,m=n?t.yLabelMax:t.yLabelMin,x=t.cyFinal+o(t.px0[1],t.px1[1]),b=y-v;if(b*s>0&&(t.labelExtraY=b),Array.isArray(e.pull))for(u=0;u<d.length;u++)(f=d[u])===t||(c.castOption(e.pull,t.pts)||0)>=(c.castOption(e.pull,f.pts)||0)||((t.pxmid[1]-f.pxmid[1])*s>0?(p=f.cyFinal+o(f.px0[1],f.px1[1]),(b=p-v-t.labelExtraY)*s>0&&(t.labelExtraY+=b)):(m+t.labelExtraY-x)*s>0&&(a=3*l*Math.abs(u-d.indexOf(t)),h=f.cxFinal+i(f.px0[0],f.px1[0]),(g=h+a-(t.cxFinal+t.pxmid[0])-t.labelExtraX)*l>0&&(t.labelExtraX+=g)))}for(n=0;n<2;n++)for(a=n?y:v,o=n?Math.max:Math.min,s=n?1:-1,r=0;r<2;r++){for(i=r?Math.max:Math.min,l=r?1:-1,(u=t[n][r]).sort(a),f=t[1-n][r],d=f.concat(u),h=[],p=0;p<u.length;p++)void 0!==u[p].yLabelMid&&h.push(u[p]);for(g=!1,p=0;n&&p<f.length;p++)if(void 0!==f[p].yLabelMid){g=f[p];break}for(p=0;p<h.length;p++){var x=p&&h[p-1];g&&!p&&(x=g),m(h[p],x)}}}(y,g),p.each(function(t){if(t.labelExtraX||t.labelExtraY){var e=n.select(this),r=e.select("g.slicetext text");r.attr("transform","translate("+t.labelExtraX+","+t.labelExtraY+")"+r.attr("transform"));var a=t.cxFinal+t.pxmid[0],o="M"+a+","+(t.cyFinal+t.pxmid[1]),l=(t.yLabelMax-t.yLabelMin)*(t.pxmid[0]<0?-1:1)/4;if(t.labelExtraX){var s=t.labelExtraX*t.pxmid[1]/t.pxmid[0],c=t.yLabelMid+t.labelExtraY-(t.cyFinal+t.pxmid[1]);Math.abs(s)>Math.abs(c)?o+="l"+c*t.pxmid[0]/t.pxmid[1]+","+c+"H"+(a+t.labelExtraX+l):o+="l"+t.labelExtraX+","+s+"v"+(c-s)+"h"+l}else o+="V"+(t.yLabelMid+t.labelExtraY)+"h"+l;e.append("path").classed("textline",!0).call(i.stroke,g.outsidetextfont.color).attr({"stroke-width":Math.min(2,g.outsidetextfont.size/8),d:o,fill:"none"})}})})}),setTimeout(function(){p.selectAll("tspan").each(function(){var t=n.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":45,"../../components/drawing":70,"../../components/fx":87,"../../lib":163,"../../lib/svg_text_utils":184,"./event_data":305,"./helpers":306,d3:10}],311:[function(t,e,r){"use strict";var n=t("d3"),a=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0].trace,r=n.select(this);r.style({opacity:e.opacity}),r.selectAll("path.surface").each(function(t){n.select(this).call(a,t,e)})})}},{"./style_one":312,d3:10}],312:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("./helpers").castOption;e.exports=function(t,e,r){var i=r.marker.line,o=a(i.color,e.pts)||n.defaultLine,l=a(i.width,e.pts)||0;t.style({"stroke-width":l}).call(n.fill,e.color).call(n.stroke,o)}},{"../../components/color":45,"./helpers":306}],313:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e){for(var r=0;r<t.length;r++)t[r].i=r;n.mergeArray(e.text,t,"tx"),n.mergeArray(e.hovertext,t,"htx"),n.mergeArray(e.customdata,t,"data"),n.mergeArray(e.textposition,t,"tp"),e.textfont&&(n.mergeArray(e.textfont.size,t,"ts"),n.mergeArray(e.textfont.color,t,"tc"),n.mergeArray(e.textfont.family,t,"tf"));var a=e.marker;if(a){n.mergeArray(a.size,t,"ms"),n.mergeArray(a.opacity,t,"mo"),n.mergeArray(a.symbol,t,"mx"),n.mergeArray(a.color,t,"mc");var i=a.line;a.line&&(n.mergeArray(i.color,t,"mlc"),n.mergeArray(i.width,t,"mlw"));var o=a.gradient;o&&"none"!==o.type&&(n.mergeArray(o.type,t,"mgt"),n.mergeArray(o.color,t,"mgc"))}}},{"../../lib":163}],314:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),a=t("../../components/colorbar/attributes"),i=t("../../plots/font_attributes"),o=t("../../components/drawing/attributes").dash,l=t("../../components/drawing"),s=(t("./constants"),t("../../lib/extend").extendFlat);e.exports={x:{valType:"data_array",editType:"calc+clearAxisTypes"},x0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dx:{valType:"number",dflt:1,editType:"calc"},y:{valType:"data_array",editType:"calc+clearAxisTypes"},y0:{valType:"any",dflt:0,editType:"calc+clearAxisTypes"},dy:{valType:"number",dflt:1,editType:"calc"},text:{valType:"string",dflt:"",arrayOk:!0,editType:"calc"},hovertext:{valType:"string",dflt:"",arrayOk:!0,editType:"style"},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"],editType:"calc"},hoveron:{valType:"flaglist",flags:["points","fills"],editType:"style"},line:{color:{valType:"color",editType:"style"},width:{valType:"number",min:0,dflt:2,editType:"style"},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear",editType:"plot"},smoothing:{valType:"number",min:0,max:1.3,dflt:1,editType:"plot"},dash:s({},o,{editType:"style"}),simplify:{valType:"boolean",dflt:!0,editType:"plot"},editType:"plot"},connectgaps:{valType:"boolean",dflt:!1,editType:"calc"},cliponaxis:{valType:"boolean",dflt:!0,editType:"plot"},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx","toself","tonext"],dflt:"none",editType:"calc"},fillcolor:{valType:"color",editType:"style"},marker:s({symbol:{valType:"enumerated",values:l.symbolList,dflt:"circle",arrayOk:!0,editType:"style"},opacity:{valType:"number",min:0,max:1,arrayOk:!0,editType:"style"},size:{valType:"number",min:0,dflt:6,arrayOk:!0,editType:"calcIfAutorange"},maxdisplayed:{valType:"number",min:0,dflt:0,editType:"plot"},sizeref:{valType:"number",dflt:1,editType:"calc"},sizemin:{valType:"number",min:0,dflt:0,editType:"calc"},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter",editType:"calc"},colorbar:a,line:s({width:{valType:"number",min:0,arrayOk:!0,editType:"style"},editType:"calc"},n("marker.line")),gradient:{type:{valType:"enumerated",values:["radial","horizontal","vertical","none"],arrayOk:!0,dflt:"none",editType:"calc"},color:{valType:"color",arrayOk:!0,editType:"calc"},editType:"calc"},editType:"calc"},n("marker")),selected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},unselected:{marker:{opacity:{valType:"number",min:0,max:1,editType:"style"},color:{valType:"color",editType:"style"},size:{valType:"number",min:0,editType:"style"},editType:"style"},textfont:{color:{valType:"color",editType:"style"},editType:"style"},editType:"style"},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0,editType:"calc"},textfont:i({editType:"calc",colorEditType:"style",arrayOk:!0}),r:{valType:"data_array",editType:"calc"},t:{valType:"data_array",editType:"calc"}}},{"../../components/colorbar/attributes":46,"../../components/colorscale/attributes":52,"../../components/drawing":70,"../../components/drawing/attributes":69,"../../lib/extend":157,"../../plots/font_attributes":233,"./constants":319}],315:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),a=t("../../lib").isArrayOrTypedArray,i=t("../../plots/cartesian/axes"),o=t("../../constants/numerical").BADNUM,l=t("./subtypes"),s=t("./colorscale_calc"),c=t("./arrays_to_calcdata"),u=t("./calc_selection");function f(t,e,r,n,a,o,s){var c=e._length;r._minDtick=0,n._minDtick=0;var u={padded:!0},f={padded:!0};s&&(u.ppad=f.ppad=s),!("tozerox"===e.fill||"tonextx"===e.fill&&t.firstscatter)||a[0]===a[c-1]&&o[0]===o[c-1]?(e.error_y||{}).visible||-1===["tonexty","tozeroy"].indexOf(e.fill)&&(l.hasMarkers(e)||l.hasText(e))||(u.padded=!1,u.ppad=0):u.tozero=!0,!("tozeroy"===e.fill||"tonexty"===e.fill&&t.firstscatter)||a[0]===a[c-1]&&o[0]===o[c-1]?-1!==["tonextx","tozerox"].indexOf(e.fill)&&(f.padded=!1):f.tozero=!0,i.expand(r,a,u),i.expand(n,o,f)}function d(t,e){if(l.hasMarkers(t)){var r,n=t.marker,o=1.6*(t.marker.sizeref||1);if(r="area"===t.marker.sizemode?function(t){return Math.max(Math.sqrt((t||0)/o),3)}:function(t){return Math.max((t||0)/o,3)},a(n.size)){var s={type:"linear"};i.setConvert(s);for(var c=s.makeCalcdata(t.marker,"size"),u=new Array(e),f=0;f<e;f++)u[f]=r(c[f]);return u}return r(n.size)}}e.exports={calc:function(t,e){var r=i.getFromId(t,e.xaxis||"x"),a=i.getFromId(t,e.yaxis||"y"),l=r.makeCalcdata(e,"x"),p=a.makeCalcdata(e,"y"),h=e._length,g=new Array(h);f(t,e,r,a,l,p,d(e,h));for(var y=0;y<h;y++)g[y]=n(l[y])&&n(p[y])?{x:l[y],y:p[y]}:{x:o,y:o},e.ids&&(g[y].id=String(e.ids[y]));return c(g,e),s(e),u(g,e),t.firstscatter=!1,g},calcMarkerSize:d,calcAxisExpansion:f}},{"../../constants/numerical":145,"../../lib":163,"../../plots/cartesian/axes":207,"./arrays_to_calcdata":313,"./calc_selection":316,"./colorscale_calc":318,"./subtypes":336,"fast-isnumeric":13}],316:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e){n.isArrayOrTypedArray(e.selectedpoints)&&n.tagSelected(t,e)}},{"../../lib":163}],317:[function(t,e,r){"use strict";e.exports=function(t){for(var e=0;e<t.length;e++){var r=t[e];if("scatter"===r.type){var n=r.fill;if("none"!==n&&"toself"!==n&&(r.opacity=void 0,"tonexty"===n||"tonextx"===n))for(var a=e-1;a>=0;a--){var i=t[a];if("scatter"===i.type&&i.xaxis===r.xaxis&&i.yaxis===r.yaxis){i.opacity=void 0;break}}}}}},{}],318:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/calc"),i=t("./subtypes");e.exports=function(t){i.hasLines(t)&&n(t,"line")&&a(t,t.line.color,"line","c"),i.hasMarkers(t)&&(n(t,"marker")&&a(t,t.marker.color,"marker","c"),n(t,"marker.line")&&a(t,t.marker.line.color,"marker.line","c"))}},{"../../components/colorscale/calc":53,"../../components/colorscale/has_colorscale":59,"./subtypes":336}],319:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20}},{}],320:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../registry"),i=t("./attributes"),o=t("./constants"),l=t("./subtypes"),s=t("./xy_defaults"),c=t("./marker_defaults"),u=t("./line_defaults"),f=t("./line_shape_defaults"),d=t("./text_defaults"),p=t("./fillcolor_defaults");e.exports=function(t,e,r,h){function g(r,a){return n.coerce(t,e,i,r,a)}var y=s(t,e,h,g),v=y<o.PTS_LINESONLY?"lines+markers":"lines";if(y){g("text"),g("hovertext"),g("mode",v),l.hasLines(e)&&(u(t,e,r,h,g),f(t,e,g),g("connectgaps"),g("line.simplify")),l.hasMarkers(e)&&c(t,e,r,h,g,{gradient:!0}),l.hasText(e)&&d(t,e,h,g);var m=[];(l.hasMarkers(e)||l.hasText(e))&&(g("cliponaxis"),g("marker.maxdisplayed"),m.push("points")),g("fill"),"none"!==e.fill&&(p(t,e,r,g),l.hasLines(e)||f(t,e,g)),"tonext"!==e.fill&&"toself"!==e.fill||m.push("fills"),g("hoveron",m.join("+")||"points");var x=a.getComponentMethod("errorbars","supplyDefaults");x(t,e,r,{axis:"y"}),x(t,e,r,{axis:"x",inherit:"y"}),n.coerceSelectionMarkerOpacity(e,g)}else e.visible=!1}},{"../../lib":163,"../../registry":247,"./attributes":314,"./constants":319,"./fillcolor_defaults":322,"./line_defaults":326,"./line_shape_defaults":328,"./marker_defaults":332,"./subtypes":336,"./text_defaults":337,"./xy_defaults":338}],321:[function(t,e,r){"use strict";var n=t("../../lib");function a(t){return t||0===t}e.exports=function(t,e,r){var i=Array.isArray(r)?function(t){r.push(t)}:function(t){r.text=t},o=n.extractOption(t,e,"htx","hovertext");if(a(o))return i(o);var l=n.extractOption(t,e,"tx","text");return a(l)?i(l):void 0}},{"../../lib":163}],322:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("../../lib").isArrayOrTypedArray;e.exports=function(t,e,r,i){var o=!1;if(e.marker){var l=e.marker.color,s=(e.marker.line||{}).color;l&&!a(l)?o=l:s&&!a(s)&&(o=s)}i("fillcolor",n.addOpacity((e.line||{}).color||o||r,.5))}},{"../../components/color":45,"../../lib":163}],323:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("./subtypes");e.exports=function(t,e){var r,i;if("lines"===t.mode)return(r=t.line.color)&&n.opacity(r)?r:t.fillcolor;if("none"===t.mode)return t.fill?t.fillcolor:"";var o=e.mcc||(t.marker||{}).color,l=e.mlcc||((t.marker||{}).line||{}).color;return(i=o&&n.opacity(o)?o:l&&n.opacity(l)&&(e.mlw||((t.marker||{}).line||{}).width)?l:"")?n.opacity(i)<.3?n.addOpacity(i,.3):i:(r=(t.line||{}).color)&&n.opacity(r)&&a.hasLines(t)&&t.line.width?r:t.fillcolor}},{"../../components/color":45,"./subtypes":336}],324:[function(t,e,r){"use strict";var n=t("../../lib"),a=t("../../components/fx"),i=t("../../registry"),o=t("./get_trace_color"),l=t("../../components/color"),s=t("./fill_hover_text");e.exports=function(t,e,r,c){var u=t.cd,f=u[0].trace,d=t.xa,p=t.ya,h=d.c2p(e),g=p.c2p(r),y=[h,g],v=f.hoveron||"",m=-1!==f.mode.indexOf("markers")?3:.5;if(-1!==v.indexOf("points")){var x=function(t){var e=Math.max(m,t.mrc||0),r=d.c2p(t.x)-h,n=p.c2p(t.y)-g;return Math.max(Math.sqrt(r*r+n*n)-e,1-m/e)},b=a.getDistanceFunction(c,function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(d.c2p(t.x)-h);return n<e?r*n/e:n-e+r},function(t){var e=Math.max(3,t.mrc||0),r=1-1/e,n=Math.abs(p.c2p(t.y)-g);return n<e?r*n/e:n-e+r},x);if(a.getClosest(u,b,t),!1!==t.index){var _=u[t.index],w=d.c2p(_.x,!0),k=p.c2p(_.y,!0),M=_.mrc||1;return n.extendFlat(t,{color:o(f,_),x0:w-M,x1:w+M,xLabelVal:_.x,y0:k-M,y1:k+M,yLabelVal:_.y,spikeDistance:x(_)}),s(_,f,t),i.getComponentMethod("errorbars","hoverInfo")(_,f,t),[t]}}if(-1!==v.indexOf("fills")&&f._polygons){var T,A,L,C,S,O,P,D,z,E=f._polygons,I=[],N=!1,R=1/0,F=-1/0,j=1/0,B=-1/0;for(T=0;T<E.length;T++)(L=E[T]).contains(y)&&(N=!N,I.push(L),j=Math.min(j,L.ymin),B=Math.max(B,L.ymax));if(N){var H=((j=Math.max(j,0))+(B=Math.min(B,p._length)))/2;for(T=0;T<I.length;T++)for(C=I[T].pts,A=1;A<C.length;A++)(D=C[A-1][1])>H!=(z=C[A][1])>=H&&(O=C[A-1][0],P=C[A][0],z-D&&(S=O+(P-O)*(H-D)/(z-D),R=Math.min(R,S),F=Math.max(F,S)));R=Math.max(R,0),F=Math.min(F,d._length);var q=l.defaultLine;return l.opacity(f.fillcolor)?q=f.fillcolor:l.opacity((f.line||{}).color)&&(q=f.line.color),n.extendFlat(t,{distance:t.maxHoverDistance,x0:R,x1:F,y0:H,y1:H,color:q}),delete t.index,f.text&&!Array.isArray(f.text)?t.text=String(f.text):t.text=f.name,[t]}}}},{"../../components/color":45,"../../components/fx":87,"../../lib":163,"../../registry":247,"./fill_hover_text":321,"./get_trace_color":323}],325:[function(t,e,r){"use strict";var n={},a=t("./subtypes");n.hasLines=a.hasLines,n.hasMarkers=a.hasMarkers,n.hasText=a.hasText,n.isBubble=a.isBubble,n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.cleanData=t("./clean_data"),n.calc=t("./calc").calc,n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.colorbar=t("./marker_colorbar"),n.style=t("./style").style,n.styleOnSelect=t("./style").styleOnSelect,n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.animatable=!0,n.moduleType="trace",n.name="scatter",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","svg","symbols","errorBarsOK","showLegend","scatter-like","zoomScale"],n.meta={},e.exports=n},{"../../plots/cartesian":218,"./arrays_to_calcdata":313,"./attributes":314,"./calc":315,"./clean_data":317,"./defaults":320,"./hover":324,"./marker_colorbar":331,"./plot":333,"./select":334,"./style":335,"./subtypes":336}],326:[function(t,e,r){"use strict";var n=t("../../lib").isArrayOrTypedArray,a=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,l,s){var c=(t.marker||{}).color;(l("line.color",r),a(t,"line"))?i(t,e,o,l,{prefix:"line.",cLetter:"c"}):l("line.color",!n(c)&&c||r);l("line.width"),(s||{}).noDash||l("line.dash")}},{"../../components/colorscale/defaults":55,"../../components/colorscale/has_colorscale":59,"../../lib":163}],327:[function(t,e,r){"use strict";var n=t("../../constants/numerical").BADNUM,a=t("../../lib"),i=a.segmentsIntersect,o=a.constrain,l=t("./constants");e.exports=function(t,e){var r,s,c,u,f,d,p,h,g,y,v,m,x,b,_,w,k,M,T=e.xaxis,A=e.yaxis,L=e.connectGaps,C=e.baseTolerance,S=e.shape,O="linear"===S,P=[],D=l.minTolerance,z=new Array(t.length),E=0;function I(e){var r=t[e];if(!r)return!1;var a=T.c2p(r.x),i=A.c2p(r.y);return a===n||i===n?r.intoCenter||!1:[a,i]}function N(t,e,r,n){var a=r-t,i=n-e,o=.5-t,l=.5-e,s=a*a+i*i,c=a*o+i*l;if(c>0&&c<s){var u=o*i-l*a;if(u*u<s)return!0}}function R(t,e){var r=t[0]/T._length,n=t[1]/A._length,a=Math.max(0,-r,r-1,-n,n-1);return a&&void 0!==k&&N(r,n,k,M)&&(a=0),a&&e&&N(r,n,e[0]/T._length,e[1]/A._length)&&(a=0),(1+l.toleranceGrowth*a)*C}function F(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}var j,B,H,q,V,U,G,Y=l.maxScreensAway,X=-T._length*Y,Z=T._length*(1+Y),W=-A._length*Y,Q=A._length*(1+Y),J=[[X,W,Z,W],[Z,W,Z,Q],[Z,Q,X,Q],[X,Q,X,W]];function $(t){if(t[0]<X||t[0]>Z||t[1]<W||t[1]>Q)return[o(t[0],X,Z),o(t[1],W,Q)]}function K(t,e){return t[0]===e[0]&&(t[0]===X||t[0]===Z)||(t[1]===e[1]&&(t[1]===W||t[1]===Q)||void 0)}function tt(t,e,r){return function(n,i){var o=$(n),l=$(i),s=[];if(o&&l&&K(o,l))return s;o&&s.push(o),l&&s.push(l);var c=2*a.constrain((n[t]+i[t])/2,e,r)-((o||n)[t]+(l||i)[t]);c&&((o&&l?c>0==o[t]>l[t]?o:l:o||l)[t]+=c);return s}}function et(t){var e=t[0],r=t[1],n=e===z[E-1][0],a=r===z[E-1][1];if(!n||!a)if(E>1){var i=e===z[E-2][0],o=r===z[E-2][1];n&&(e===X||e===Z)&&i?o?E--:z[E-1]=t:a&&(r===W||r===Q)&&o?i?E--:z[E-1]=t:z[E++]=t}else z[E++]=t}function rt(t){z[E-1][0]!==t[0]&&z[E-1][1]!==t[1]&&et([H,q]),et(t),V=null,H=q=0}function nt(t){if(k=t[0]/T._length,M=t[1]/A._length,j=t[0]<X?X:t[0]>Z?Z:0,B=t[1]<W?W:t[1]>Q?Q:0,j||B){if(E)if(V){var e=G(V,t);e.length>1&&(rt(e[0]),z[E++]=e[1])}else U=G(z[E-1],t)[0],z[E++]=U;else z[E++]=[j||t[0],B||t[1]];var r=z[E-1];j&&B&&(r[0]!==j||r[1]!==B)?(V&&(H!==j&&q!==B?et(H&&q?(n=V,i=(a=t)[0]-n[0],o=(a[1]-n[1])/i,(n[1]*a[0]-a[1]*n[0])/i>0?[o>0?X:Z,Q]:[o>0?Z:X,W]):[H||j,q||B]):H&&q&&et([H,q])),et([j,B])):H-j&&q-B&&et([j||H,B||q]),V=t,H=j,q=B}else V&&rt(G(V,t)[0]),z[E++]=t;var n,a,i,o}for("linear"===S||"spline"===S?G=function(t,e){for(var r=[],n=0,a=0;a<4;a++){var o=J[a],l=i(t[0],t[1],e[0],e[1],o[0],o[1],o[2],o[3]);l&&(!n||Math.abs(l.x-r[0][0])>1||Math.abs(l.y-r[0][1])>1)&&(l=[l.x,l.y],n&&F(l,t)<F(r[0],t)?r.unshift(l):r.push(l),n++)}return r}:"hv"===S||"vh"===S?G=function(t,e){var r=[],n=$(t),a=$(e);return n&&a&&K(n,a)?r:(n&&r.push(n),a&&r.push(a),r)}:"hvh"===S?G=tt(0,X,Z):"vhv"===S&&(G=tt(1,W,Q)),r=0;r<t.length;r++)if(s=I(r)){for(E=0,V=null,nt(s),r++;r<t.length;r++){if(!(u=I(r))){if(L)continue;break}if(O&&e.simplify){var at=I(r+1);if(!((y=F(u,s))<R(u,at)*D)){for(h=[(u[0]-s[0])/y,(u[1]-s[1])/y],f=s,v=y,m=b=_=0,p=!1,c=u,r++;r<t.length;r++){if(d=at,at=I(r+1),!d){if(L)continue;break}if(w=(g=[d[0]-s[0],d[1]-s[1]])[0]*h[1]-g[1]*h[0],b=Math.min(b,w),(_=Math.max(_,w))-b>R(d,at))break;c=d,(x=g[0]*h[0]+g[1]*h[1])>v?(v=x,u=d,p=!1):x<m&&(m=x,f=d,p=!0)}if(p?(nt(u),c!==f&&nt(f)):(f!==s&&nt(f),c!==u&&nt(u)),nt(c),r>=t.length||!d)break;nt(d),s=d}}else nt(u)}V&&et([H||V[0],q||V[1]]),P.push(z.slice(0,E))}return P}},{"../../constants/numerical":145,"../../lib":163,"./constants":319}],328:[function(t,e,r){"use strict";e.exports=function(t,e,r){"spline"===r("line.shape")&&r("line.smoothing")}},{}],329:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,a,i=null;for(a=0;a<r.length;++a)!0===(n=r[a][0].trace).visible?(n._nexttrace=null,-1!==["tonextx","tonexty","tonext"].indexOf(n.fill)&&(n._prevtrace=i,i&&(i._nexttrace=n)),i=n):n._prevtrace=n._nexttrace=null}},{}],330:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t){var e=t.marker,r=e.sizeref||1,a=e.sizemin||0,i="area"===e.sizemode?function(t){return Math.sqrt(t/r)}:function(t){return t/r};return function(t){var e=i(t/2);return n(e)&&e>0?Math.max(e,a):0}}},{"fast-isnumeric":13}],331:[function(t,e,r){"use strict";e.exports={container:"marker",min:"cmin",max:"cmax"}},{}],332:[function(t,e,r){"use strict";var n=t("../../components/color"),a=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,l,s,c){var u=o.isBubble(t),f=(t.line||{}).color;(c=c||{},f&&(r=f),s("marker.symbol"),s("marker.opacity",u?.7:1),s("marker.size"),s("marker.color",r),a(t,"marker")&&i(t,e,l,s,{prefix:"marker.",cLetter:"c"}),c.noSelect||(s("selected.marker.color"),s("unselected.marker.color"),s("selected.marker.size"),s("unselected.marker.size")),c.noLine||(s("marker.line.color",f&&!Array.isArray(f)&&e.marker.color!==f?f:u?n.background:n.defaultLine),a(t,"marker.line")&&i(t,e,l,s,{prefix:"marker.line.",cLetter:"c"}),s("marker.line.width",u?1:0)),u&&(s("marker.sizeref"),s("marker.sizemin"),s("marker.sizemode")),c.gradient)&&("none"!==s("marker.gradient.type")&&s("marker.gradient.color"))}},{"../../components/color":45,"../../components/colorscale/defaults":55,"../../components/colorscale/has_colorscale":59,"./subtypes":336}],333:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../registry"),i=t("../../lib"),o=t("../../components/drawing"),l=t("./subtypes"),s=t("./line_points"),c=t("./link_traces"),u=t("../../lib/polygon").tester;function f(t,e,r,c,f,d,p){var h,g;!function(t,e,r,a,o){var s=r.xaxis,c=r.yaxis,u=n.extent(i.simpleMap(s.range,s.r2c)),f=n.extent(i.simpleMap(c.range,c.r2c)),d=a[0].trace;if(!l.hasMarkers(d))return;var p=d.marker.maxdisplayed;if(0===p)return;var h=a.filter(function(t){return t.x>=u[0]&&t.x<=u[1]&&t.y>=f[0]&&t.y<=f[1]}),g=Math.ceil(h.length/p),y=0;o.forEach(function(t,r){var n=t[0].trace;l.hasMarkers(n)&&n.marker.maxdisplayed>0&&r<e&&y++});var v=Math.round(y*g/3+Math.floor(y/3)*g/7.1);a.forEach(function(t){delete t.vis}),h.forEach(function(t,e){0===Math.round((e+v)%g)&&(t.vis=!0)})}(0,e,r,c,f);var y=!!p&&p.duration>0;function v(t){return y?t.transition():t}var m=r.xaxis,x=r.yaxis,b=c[0].trace,_=b.line,w=n.select(d);if(a.getComponentMethod("errorbars","plot")(w,r,p),!0===b.visible){var k,M;v(w).style("opacity",b.opacity);var T=b.fill.charAt(b.fill.length-1);"x"!==T&&"y"!==T&&(T=""),r.isRangePlot||(c[0].node3=w);var A="",L=[],C=b._prevtrace;C&&(A=C._prevRevpath||"",M=C._nextFill,L=C._polygons);var S,O,P,D,z,E,I,N,R,F="",j="",B=[],H=i.noop;if(k=b._ownFill,l.hasLines(b)||"none"!==b.fill){for(M&&M.datum(c),-1!==["hv","vh","hvh","vhv"].indexOf(_.shape)?(P=o.steps(_.shape),D=o.steps(_.shape.split("").reverse().join(""))):P=D="spline"===_.shape?function(t){var e=t[t.length-1];return t.length>1&&t[0][0]===e[0]&&t[0][1]===e[1]?o.smoothclosed(t.slice(1),_.smoothing):o.smoothopen(t,_.smoothing)}:function(t){return"M"+t.join("L")},z=function(t){return D(t.reverse())},B=s(c,{xaxis:m,yaxis:x,connectGaps:b.connectgaps,baseTolerance:Math.max(_.width||1,3)/4,shape:_.shape,simplify:_.simplify}),R=b._polygons=new Array(B.length),g=0;g<B.length;g++)b._polygons[g]=u(B[g]);B.length&&(E=B[0][0],N=(I=B[B.length-1])[I.length-1]),H=function(t){return function(e){if(S=P(e),O=z(e),F?T?(F+="L"+S.substr(1),j=O+"L"+j.substr(1)):(F+="Z"+S,j=O+"Z"+j):(F=S,j=O),l.hasLines(b)&&e.length>1){var r=n.select(this);if(r.datum(c),t)v(r.style("opacity",0).attr("d",S).call(o.lineGroupStyle)).style("opacity",1);else{var a=v(r);a.attr("d",S),o.singleLineStyle(c,a)}}}}}var q=w.selectAll(".js-line").data(B);v(q.exit()).style("opacity",0).remove(),q.each(H(!1)),q.enter().append("path").classed("js-line",!0).style("vector-effect","non-scaling-stroke").call(o.lineGroupStyle).each(H(!0)),o.setClipUrl(q,r.layerClipId),B.length?(k?E&&N&&(T?("y"===T?E[1]=N[1]=x.c2p(0,!0):"x"===T&&(E[0]=N[0]=m.c2p(0,!0)),v(k).attr("d","M"+N+"L"+E+"L"+F.substr(1)).call(o.singleFillStyle)):v(k).attr("d",F+"Z").call(o.singleFillStyle)):M&&("tonext"===b.fill.substr(0,6)&&F&&A?("tonext"===b.fill?v(M).attr("d",F+"Z"+A+"Z").call(o.singleFillStyle):v(M).attr("d",F+"L"+A.substr(1)+"Z").call(o.singleFillStyle),b._polygons=b._polygons.concat(L)):(U(M),b._polygons=null)),b._prevRevpath=j,b._prevPolygons=R):(k?U(k):M&&U(M),b._polygons=b._prevRevpath=b._prevPolygons=null);var V=w.selectAll(".points");h=V.data([c]),V.each(W),h.enter().append("g").classed("points",!0).each(W),h.exit().remove(),h.each(function(t){var e=!1===t[0].trace.cliponaxis;o.setClipUrl(n.select(this),e?null:r.layerClipId)})}function U(t){v(t).attr("d","M0,0Z")}function G(t){return t.filter(function(t){return t.vis})}function Y(t){return t.id}function X(t){if(t.ids)return Y}function Z(){return!1}function W(e){var a,s=e[0].trace,c=n.select(this),u=l.hasMarkers(s),f=l.hasText(s),d=X(s),p=Z,h=Z;u&&(p=s.marker.maxdisplayed||s._needsCull?G:i.identity),f&&(h=s.marker.maxdisplayed||s._needsCull?G:i.identity);var g,b=(a=c.selectAll("path.point").data(p,d)).enter().append("path").classed("point",!0);y&&b.call(o.pointStyle,s,t).call(o.translatePoints,m,x).style("opacity",0).transition().style("opacity",1),a.order(),u&&(g=o.makePointStyleFns(s)),a.each(function(e){var a=n.select(this),i=v(a);o.translatePoint(e,i,m,x)?(o.singlePointStyle(e,i,s,g,t),r.layerClipId&&o.hideOutsideRangePoint(e,i,m,x,s.xcalendar,s.ycalendar),s.customdata&&a.classed("plotly-customdata",null!==e.data&&void 0!==e.data)):i.remove()}),y?a.exit().transition().style("opacity",0).remove():a.exit().remove(),(a=c.selectAll("g").data(h,d)).enter().append("g").classed("textpoint",!0).append("text"),a.order(),a.each(function(t){var e=n.select(this),a=v(e.select("text"));o.translatePoint(t,a,m,x)?r.layerClipId&&o.hideOutsideRangePoint(t,e,m,x,s.xcalendar,s.ycalendar):e.remove()}),a.selectAll("text").call(o.textPointStyle,s,t).each(function(t){var e=m.c2p(t.x),r=x.c2p(t.y);n.select(this).selectAll("tspan.line").each(function(){v(n.select(this)).attr({x:e,y:r})})}),a.exit().remove()}}e.exports=function(t,e,r,a,i,l){var s,u,d,p,h=!i,g=!!i&&i.duration>0;for((d=a.selectAll("g.trace").data(r,function(t){return t[0].trace.uid})).enter().append("g").attr("class",function(t){return"trace scatter trace"+t[0].trace.uid}).style("stroke-miterlimit",2),c(t,e,r),function(t,e,r){var a;e.selectAll("g.trace").each(function(t){var e=n.select(this);if((a=t[0].trace)._nexttrace){if(a._nextFill=e.select(".js-fill.js-tonext"),!a._nextFill.size()){var i=":first-child";e.select(".js-fill.js-tozero").size()&&(i+=" + *"),a._nextFill=e.insert("path",i).attr("class","js-fill js-tonext")}}else e.selectAll(".js-fill.js-tonext").remove(),a._nextFill=null;a.fill&&("tozero"===a.fill.substr(0,6)||"toself"===a.fill||"to"===a.fill.substr(0,2)&&!a._prevtrace)?(a._ownFill=e.select(".js-fill.js-tozero"),a._ownFill.size()||(a._ownFill=e.insert("path",":first-child").attr("class","js-fill js-tozero"))):(e.selectAll(".js-fill.js-tozero").remove(),a._ownFill=null),e.selectAll(".js-fill").call(o.setClipUrl,r.layerClipId)})}(0,a,e),s=0,u={};s<r.length;s++)u[r[s][0].trace.uid]=s;(a.selectAll("g.trace").sort(function(t,e){return u[t[0].trace.uid]>u[e[0].trace.uid]?1:-1}),g)?(l&&(p=l()),n.transition().duration(i.duration).ease(i.easing).each("end",function(){p&&p()}).each("interrupt",function(){p&&p()}).each(function(){a.selectAll("g.trace").each(function(n,a){f(t,a,e,n,r,this,i)})})):a.selectAll("g.trace").each(function(n,a){f(t,a,e,n,r,this,i)});h&&d.exit().remove(),a.selectAll("path:not([d])").remove()}},{"../../components/drawing":70,"../../lib":163,"../../lib/polygon":175,"../../registry":247,"./line_points":327,"./link_traces":329,"./subtypes":336,d3:10}],334:[function(t,e,r){"use strict";var n=t("./subtypes");e.exports=function(t,e){var r,a,i,o,l=t.cd,s=t.xaxis,c=t.yaxis,u=[],f=l[0].trace;if(!n.hasMarkers(f)&&!n.hasText(f))return[];if(!1===e)for(r=0;r<l.length;r++)l[r].selected=0;else for(r=0;r<l.length;r++)a=l[r],i=s.c2p(a.x),o=c.c2p(a.y),e.contains([i,o])?(u.push({pointNumber:r,x:s.c2d(a.x),y:c.c2d(a.y)}),a.selected=1):a.selected=0;return u}},{"./subtypes":336}],335:[function(t,e,r){"use strict";var n=t("d3"),a=t("../../components/drawing"),i=t("../../registry");function o(t,e,r){a.pointStyle(t.selectAll("path.point"),e,r),a.textPointStyle(t.selectAll("text"),e,r)}e.exports={style:function(t,e){var r=e?e[0].node3:n.select(t).selectAll("g.trace.scatter");r.style("opacity",function(t){return t[0].trace.opacity}),r.selectAll("g.points").each(function(e){o(n.select(this),e.trace||e[0].trace,t)}),r.selectAll("g.trace path.js-line").call(a.lineGroupStyle),r.selectAll("g.trace path.js-fill").call(a.fillGroupStyle),i.getComponentMethod("errorbars","style")(r)},stylePoints:o,styleOnSelect:function(t,e){var r=e[0].node3,n=e[0].trace;n.selectedpoints?(a.selectedPointStyle(r.selectAll("path.point"),n),a.selectedTextStyle(r.selectAll("text"),n)):o(r,n,t)}}},{"../../components/drawing":70,"../../registry":247,d3:10}],336:[function(t,e,r){"use strict";var n=t("../../lib");e.exports={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&(t.mode&&-1!==t.mode.indexOf("markers")||"splom"===t.type)},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return n.isPlainObject(t.marker)&&n.isArrayOrTypedArray(t.marker.size)}}},{"../../lib":163}],337:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,a,i){i=i||{},a("textposition"),n.coerceFont(a,"textfont",r.font),i.noSelect||(a("selected.textfont.color"),a("unselected.textfont.color"))}},{"../../lib":163}],338:[function(t,e,r){"use strict";var n=t("../../registry");e.exports=function(t,e,r,a){var i,o=a("x"),l=a("y");if(n.getComponentMethod("calendars","handleTraceDefaults")(t,e,["x","y"],r),o)l?i=Math.min(o.length,l.length):(i=o.length,a("y0"),a("dy"));else{if(!l)return 0;i=e.y.length,a("x0"),a("dx")}return e._length=i,i}},{"../../registry":247}]},{},[7])(7)});
test/focus-first-suggestion-clear-on-enter/AutosuggestApp.js
CoreFiling/react-autosuggest
import React, { Component } from 'react'; import sinon from 'sinon'; import Autosuggest from '../../src/Autosuggest'; import languages from '../plain-list/languages'; import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js'; import { addEvent } from '../helpers'; const getMatchingLanguages = value => { const escapedValue = escapeRegexCharacters(value.trim()); const regex = new RegExp('^' + escapedValue, 'i'); return languages.filter(language => regex.test(language.name)); }; let app = null; export const getSuggestionValue = suggestion => suggestion.name; export const renderSuggestion = suggestion => ( <span>{suggestion.name}</span> ); export const onChange = sinon.spy((event, { newValue }) => { addEvent('onChange'); app.setState({ value: newValue }); }); export const onSuggestionsFetchRequested = ({ value }) => { app.setState({ suggestions: getMatchingLanguages(value) }); }; export const onSuggestionsClearRequested = () => { app.setState({ suggestions: [] }); }; export const onSuggestionSelected = sinon.spy(() => { addEvent('onSuggestionSelected'); app.setState({ value: '' }); }); export default class AutosuggestApp extends Component { constructor() { super(); app = this; this.state = { value: '', suggestions: [] }; } render() { const { value, suggestions } = this.state; const inputProps = { value, onChange }; return ( <Autosuggest suggestions={suggestions.slice()} onSuggestionsFetchRequested={onSuggestionsFetchRequested} onSuggestionsClearRequested={onSuggestionsClearRequested} onSuggestionSelected={onSuggestionSelected} getSuggestionValue={getSuggestionValue} renderSuggestion={renderSuggestion} inputProps={inputProps} highlightFirstSuggestion={true} /> ); } }
src/svg-icons/device/battery-30.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBattery30 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V15h10V5.33z"/><path d="M7 15v5.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V15H7z"/> </SvgIcon> ); DeviceBattery30 = pure(DeviceBattery30); DeviceBattery30.displayName = 'DeviceBattery30'; DeviceBattery30.muiName = 'SvgIcon'; export default DeviceBattery30;
examples/src/components/CustomRenderField.js
javier-garcia-anfix/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 CustomRenderField = React.createClass({ displayName: 'CustomRenderField', propTypes: { delimiter: React.PropTypes.string, label: React.PropTypes.string, multi: React.PropTypes.bool, }, renderOption (option) { return <span style={{ color: option.hex }}>{option.label} ({option.hex})</span>; }, renderValue (option) { return <strong style={{ color: option.hex }}>{option.label}</strong>; }, render () { var ops = [ { label: 'Red', value: 'red', hex: '#EC6230' }, { label: 'Green', value: 'green', hex: '#4ED84E' }, { label: 'Blue', value: 'blue', hex: '#6D97E2' } ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select delimiter={this.props.delimiter} multi={this.props.multi} allowCreate={true} placeholder="Select your favourite" options={ops} optionRenderer={this.renderOption} valueRenderer={this.renderValue} onChange={logChange} /> </div> ); } }); module.exports = CustomRenderField;
generators/component/templates/Component.js
gmmendezp/generator-nyssa-fe
import React, { Component } from 'react'; import { translate } from 'react-i18next'; import { style } from 'typestyle';<% if (container){%> import { connect } from 'react-redux';<% } %> export class <%= name %> extends Component { static defaultProps = { styles: {} } constructor() { super(); this.styles = { base: {} }; } render() { return ( <div className={style(this.styles.base, this.props.styles.base)}> <%= name %> </div> ); } } <% if (container) { %> const mapStateToProps = state => { return {}; } export default translate('translations')(connect(mapStateToProps)(<%= name %>));<% } else {%>export default translate('translations')(<%= name %>);<% }%>
app/private/indexerApp/imports/ui/pages/NewDocument.js
ericvrp/GameCollie
import React from 'react'; import DocumentEditor from '../components/DocumentEditor.js'; const NewDocument = () => ( <div className="NewDocument"> <h4 className="page-header">New Document</h4> <DocumentEditor /> </div> ); export default NewDocument;
app/src/components/Nav.js
alpcanaydin/github-stats-for-turkey
/* eslint-disable jsx-a11y/no-static-element-interactions */ import React, { Component } from 'react'; import { Link } from 'react-router-dom'; class Nav extends Component { constructor(props) { super(props); this.state = { isMobileMenuOpened: false }; this.handleMobileMenuVisibility = this.handleMobileMenuVisibility.bind(this); } handleMobileMenuVisibility() { this.setState({ isMobileMenuOpened: !this.state.isMobileMenuOpened }); } render() { const { isMobileMenuOpened } = this.state; return ( <nav className="nav has-shadow"> <div className="container"> <div className="nav-left"> <Link to="/" className="nav-item is-brand"> <span className="icon is-medium"> <i className="fa fa-github" /> </span> <span style={{ paddingLeft: '5px' }}>Github Türkiye İstatistikleri</span> </Link> </div> <span className="nav-toggle" onClick={this.handleMobileMenuVisibility}> <span /> <span /> <span /> </span> <div className={`nav-right nav-menu ${isMobileMenuOpened && 'is-active'}`}> <span className="nav-item"> <Link to="/?where=cities">Şehirler</Link> </span> <span className="nav-item"> <Link to="/?where=languages">Diller</Link> </span> <span className="nav-item"> <Link to="/?where=developers">Geliştirici Ara</Link> </span> <span className="nav-item"> <a href="https://github.com/alpcanaydin/github-stats-for-turkey" className="button is-dark" target="_blank" rel="noopener noreferrer" > Kaynak Kodları </a> </span> </div> </div> </nav> ); } } export default Nav;
ajax/libs/react-bootstrap/0.29.0-alpha.0/react-bootstrap.js
AMoo-Miki/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_4__, __WEBPACK_EXTERNAL_MODULE_64__) { 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 _utilsChildrenValueInputValidation = __webpack_require__(3); var _utilsChildrenValueInputValidation2 = _interopRequireDefault(_utilsChildrenValueInputValidation); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _Accordion2 = __webpack_require__(34); var _Accordion3 = _interopRequireDefault(_Accordion2); exports.Accordion = _Accordion3['default']; var _Alert2 = __webpack_require__(38); var _Alert3 = _interopRequireDefault(_Alert2); exports.Alert = _Alert3['default']; var _Badge2 = __webpack_require__(40); var _Badge3 = _interopRequireDefault(_Badge2); exports.Badge = _Badge3['default']; var _Breadcrumb2 = __webpack_require__(41); var _Breadcrumb3 = _interopRequireDefault(_Breadcrumb2); exports.Breadcrumb = _Breadcrumb3['default']; var _BreadcrumbItem2 = __webpack_require__(42); var _BreadcrumbItem3 = _interopRequireDefault(_BreadcrumbItem2); exports.BreadcrumbItem = _BreadcrumbItem3['default']; var _Button2 = __webpack_require__(52); var _Button3 = _interopRequireDefault(_Button2); exports.Button = _Button3['default']; var _ButtonGroup2 = __webpack_require__(55); var _ButtonGroup3 = _interopRequireDefault(_ButtonGroup2); exports.ButtonGroup = _ButtonGroup3['default']; var _ButtonInput2 = __webpack_require__(57); var _ButtonInput3 = _interopRequireDefault(_ButtonInput2); exports.ButtonInput = _ButtonInput3['default']; var _ButtonToolbar2 = __webpack_require__(61); var _ButtonToolbar3 = _interopRequireDefault(_ButtonToolbar2); exports.ButtonToolbar = _ButtonToolbar3['default']; var _Carousel2 = __webpack_require__(62); var _Carousel3 = _interopRequireDefault(_Carousel2); exports.Carousel = _Carousel3['default']; var _CarouselItem2 = __webpack_require__(63); var _CarouselItem3 = _interopRequireDefault(_CarouselItem2); exports.CarouselItem = _CarouselItem3['default']; var _Col2 = __webpack_require__(66); var _Col3 = _interopRequireDefault(_Col2); exports.Col = _Col3['default']; var _CollapsibleNav2 = __webpack_require__(67); var _CollapsibleNav3 = _interopRequireDefault(_CollapsibleNav2); exports.CollapsibleNav = _CollapsibleNav3['default']; var _Dropdown2 = __webpack_require__(82); var _Dropdown3 = _interopRequireDefault(_Dropdown2); exports.Dropdown = _Dropdown3['default']; var _DropdownButton2 = __webpack_require__(168); var _DropdownButton3 = _interopRequireDefault(_DropdownButton2); exports.DropdownButton = _DropdownButton3['default']; var _Glyphicon2 = __webpack_require__(60); var _Glyphicon3 = _interopRequireDefault(_Glyphicon2); exports.Glyphicon = _Glyphicon3['default']; var _Grid2 = __webpack_require__(170); var _Grid3 = _interopRequireDefault(_Grid2); exports.Grid = _Grid3['default']; var _Image2 = __webpack_require__(171); var _Image3 = _interopRequireDefault(_Image2); exports.Image = _Image3['default']; var _Input2 = __webpack_require__(172); var _Input3 = _interopRequireDefault(_Input2); exports.Input = _Input3['default']; var _Interpolate2 = __webpack_require__(175); var _Interpolate3 = _interopRequireDefault(_Interpolate2); exports.Interpolate = _Interpolate3['default']; var _Jumbotron2 = __webpack_require__(176); var _Jumbotron3 = _interopRequireDefault(_Jumbotron2); exports.Jumbotron = _Jumbotron3['default']; var _Label2 = __webpack_require__(177); var _Label3 = _interopRequireDefault(_Label2); exports.Label = _Label3['default']; var _ListGroup2 = __webpack_require__(178); var _ListGroup3 = _interopRequireDefault(_ListGroup2); exports.ListGroup = _ListGroup3['default']; var _ListGroupItem2 = __webpack_require__(179); var _ListGroupItem3 = _interopRequireDefault(_ListGroupItem2); exports.ListGroupItem = _ListGroupItem3['default']; var _MenuItem2 = __webpack_require__(180); var _MenuItem3 = _interopRequireDefault(_MenuItem2); exports.MenuItem = _MenuItem3['default']; var _Media2 = __webpack_require__(181); var _Media3 = _interopRequireDefault(_Media2); exports.Media = _Media3['default']; var _Modal2 = __webpack_require__(188); var _Modal3 = _interopRequireDefault(_Modal2); exports.Modal = _Modal3['default']; var _ModalBody2 = __webpack_require__(195); var _ModalBody3 = _interopRequireDefault(_ModalBody2); exports.ModalBody = _ModalBody3['default']; var _ModalFooter2 = __webpack_require__(198); var _ModalFooter3 = _interopRequireDefault(_ModalFooter2); exports.ModalFooter = _ModalFooter3['default']; var _ModalHeader2 = __webpack_require__(196); var _ModalHeader3 = _interopRequireDefault(_ModalHeader2); exports.ModalHeader = _ModalHeader3['default']; var _ModalTitle2 = __webpack_require__(197); var _ModalTitle3 = _interopRequireDefault(_ModalTitle2); exports.ModalTitle = _ModalTitle3['default']; var _Nav2 = __webpack_require__(214); var _Nav3 = _interopRequireDefault(_Nav2); exports.Nav = _Nav3['default']; var _Navbar2 = __webpack_require__(216); var _Navbar3 = _interopRequireDefault(_Navbar2); exports.Navbar = _Navbar3['default']; var _NavbarBrand2 = __webpack_require__(217); var _NavbarBrand3 = _interopRequireDefault(_NavbarBrand2); exports.NavbarBrand = _NavbarBrand3['default']; var _NavDropdown2 = __webpack_require__(221); var _NavDropdown3 = _interopRequireDefault(_NavDropdown2); exports.NavDropdown = _NavDropdown3['default']; var _NavItem2 = __webpack_require__(222); var _NavItem3 = _interopRequireDefault(_NavItem2); exports.NavItem = _NavItem3['default']; var _Overlay2 = __webpack_require__(223); var _Overlay3 = _interopRequireDefault(_Overlay2); exports.Overlay = _Overlay3['default']; var _OverlayTrigger2 = __webpack_require__(232); var _OverlayTrigger3 = _interopRequireDefault(_OverlayTrigger2); exports.OverlayTrigger = _OverlayTrigger3['default']; var _PageHeader2 = __webpack_require__(233); var _PageHeader3 = _interopRequireDefault(_PageHeader2); exports.PageHeader = _PageHeader3['default']; var _PageItem2 = __webpack_require__(234); var _PageItem3 = _interopRequireDefault(_PageItem2); exports.PageItem = _PageItem3['default']; var _Pager2 = __webpack_require__(235); var _Pager3 = _interopRequireDefault(_Pager2); exports.Pager = _Pager3['default']; var _Pagination2 = __webpack_require__(236); var _Pagination3 = _interopRequireDefault(_Pagination2); exports.Pagination = _Pagination3['default']; var _Panel2 = __webpack_require__(239); var _Panel3 = _interopRequireDefault(_Panel2); exports.Panel = _Panel3['default']; var _PanelGroup2 = __webpack_require__(35); var _PanelGroup3 = _interopRequireDefault(_PanelGroup2); exports.PanelGroup = _PanelGroup3['default']; var _Popover2 = __webpack_require__(240); var _Popover3 = _interopRequireDefault(_Popover2); exports.Popover = _Popover3['default']; var _ProgressBar2 = __webpack_require__(241); var _ProgressBar3 = _interopRequireDefault(_ProgressBar2); exports.ProgressBar = _ProgressBar3['default']; var _ResponsiveEmbed2 = __webpack_require__(242); var _ResponsiveEmbed3 = _interopRequireDefault(_ResponsiveEmbed2); exports.ResponsiveEmbed = _ResponsiveEmbed3['default']; var _Row2 = __webpack_require__(243); var _Row3 = _interopRequireDefault(_Row2); exports.Row = _Row3['default']; var _SafeAnchor2 = __webpack_require__(43); var _SafeAnchor3 = _interopRequireDefault(_SafeAnchor2); exports.SafeAnchor = _SafeAnchor3['default']; var _SplitButton2 = __webpack_require__(244); var _SplitButton3 = _interopRequireDefault(_SplitButton2); exports.SplitButton = _SplitButton3['default']; var _Tab2 = __webpack_require__(246); var _Tab3 = _interopRequireDefault(_Tab2); exports.Tab = _Tab3['default']; var _Table2 = __webpack_require__(250); var _Table3 = _interopRequireDefault(_Table2); exports.Table = _Table3['default']; var _Tabs2 = __webpack_require__(251); var _Tabs3 = _interopRequireDefault(_Tabs2); exports.Tabs = _Tabs3['default']; var _Thumbnail2 = __webpack_require__(252); var _Thumbnail3 = _interopRequireDefault(_Thumbnail2); exports.Thumbnail = _Thumbnail3['default']; var _Tooltip2 = __webpack_require__(253); var _Tooltip3 = _interopRequireDefault(_Tooltip2); exports.Tooltip = _Tooltip3['default']; var _Well2 = __webpack_require__(254); var _Well3 = _interopRequireDefault(_Well2); exports.Well = _Well3['default']; var _Collapse2 = __webpack_require__(68); var _Collapse3 = _interopRequireDefault(_Collapse2); exports.Collapse = _Collapse3['default']; var _Fade2 = __webpack_require__(193); var _Fade3 = _interopRequireDefault(_Fade2); exports.Fade = _Fade3['default']; var _FormControls2 = __webpack_require__(173); var _FormControls = _interopRequireWildcard(_FormControls2); exports.FormControls = _FormControls; var utils = { bootstrapUtils: _utilsBootstrapUtils2['default'], childrenValueInputValidation: _utilsChildrenValueInputValidation2['default'], createChainedFunction: _utilsCreateChainedFunction2['default'], ValidComponentChildren: _utilsValidComponentChildren2['default'] }; 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 _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports['default'] = valueValidation; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibSinglePropFrom = __webpack_require__(5); var _reactPropTypesLibSinglePropFrom2 = _interopRequireDefault(_reactPropTypesLibSinglePropFrom); function valueValidation(props, propName, componentName) { var error = _reactPropTypesLibSinglePropFrom2['default']('children', 'value')(props, propName, componentName); if (!error) { error = _react2['default'].PropTypes.node(props, propName, componentName); } return error; } module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports) { /** * 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} */ 'use strict'; exports.__esModule = true; exports['default'] = createSinglePropFromChecker; function createSinglePropFromChecker() { for (var _len = arguments.length, arrOfProps = Array(_len), _key = 0; _key < _len; _key++) { arrOfProps[_key] = arguments[_key]; } function validate(props, propName, componentName) { var usedPropCount = arrOfProps.map(function (listedProp) { return props[listedProp]; }).reduce(function (acc, curr) { return acc + (curr !== undefined ? 1 : 0); }, 0); if (usedPropCount > 1) { var first = arrOfProps[0]; var others = arrOfProps.slice(1); var message = others.join(', ') + ' and ' + first; return new Error('Invalid prop \'' + propName + '\', only one of the following ' + ('may be provided: ' + message)); } } return validate; } module.exports = exports['default']; /***/ }, /* 6 */ /***/ 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']; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); /** * Maps children that are typically specified as `props.children`, * but only iterates 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)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapValidComponents(children, func, context) { var index = 0; return _react2['default'].Children.map(children, function (child) { if (_react2['default'].isValidElement(child)) { var lastIndex = index; index++; return func.call(context, child, lastIndex); } return child; }); } /** * Iterates through 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)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachValidComponents(children, func, context) { var index = 0; return _react2['default'].Children.forEach(children, function (child) { if (_react2['default'].isValidElement(child)) { func.call(context, child, index); index++; } }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function numberOfValidComponents(children) { var count = 0; _react2['default'].Children.forEach(children, function (child) { if (_react2['default'].isValidElement(child)) { count++; } }); return count; } /** * Determine if the Child container has one or more "valid components". * * @param {?*} children Children tree container. * @returns {boolean} */ function hasValidComponent(children) { var hasValid = false; _react2['default'].Children.forEach(children, function (child) { if (!hasValid && _react2['default'].isValidElement(child)) { hasValid = true; } }); return hasValid; } function find(children, finder) { var child = undefined; forEachValidComponents(children, function (c, idx) { if (!child && finder(c, idx, children)) { child = c; } }); return child; } /** * 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)} findFunc. * @param {*} findContext Context for findContext. * @returns {array} of children that meet the findFunc return statement */ function findValidComponents(children, func, context) { var index = 0; var returnChildren = []; _react2['default'].Children.forEach(children, function (child) { if (_react2['default'].isValidElement(child)) { if (func.call(context, child, index)) { returnChildren.push(child); } index++; } }); return returnChildren; } exports['default'] = { map: mapValidComponents, forEach: forEachValidComponents, numberOf: numberOfValidComponents, find: find, findValidComponents: findValidComponents, hasValidComponent: hasValidComponent }; module.exports = exports['default']; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _styleMaps = __webpack_require__(25); var _styleMaps2 = _interopRequireDefault(_styleMaps); var _invariant = __webpack_require__(32); var _invariant2 = _interopRequireDefault(_invariant); var _warning = __webpack_require__(33); var _warning2 = _interopRequireDefault(_warning); 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) { if (props === undefined) props = {}; !(props.bsClass || '').trim() ? 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.reduce(function (result, size) { if (_styleMaps2['default'].SIZES[size] && _styleMaps2['default'].SIZES[size] !== size) { result.push(_styleMaps2['default'].SIZES[size]); } return result.concat(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) { var defaultProps = Component.defaultProps || (Component.defaultProps = {}); defaultProps.bsSize = defaultSize; } return Component; }); exports.bsSizes = bsSizes; exports['default'] = { prefix: prefix, getClassSet: function getClassSet(props) { var classes = {}; var bsClassName = prefix(props); if (bsClassName) { var bsSize = undefined; classes[bsClassName] = true; if (props.bsSize) { bsSize = _styleMaps2['default'].SIZES[props.bsSize] || bsSize; } if (bsSize) { classes[prefix(props, bsSize)] = true; } if (props.bsStyle) { if (props.bsStyle.indexOf(prefix(props)) === 0) { true ? _warning2['default'](false, // small migration convenience, since the old method required manual prefixing 'bsStyle will automatically prefix custom values with the bsClass, so there is no ' + 'need to append it manually. (bsStyle: ' + props.bsStyle + ', bsClass: ' + prefix(props) + ')') : undefined; classes[props.bsStyle] = true; } else { classes[prefix(props, props.bsStyle)] = true; } } } return classes; }, /** * Add a style variant to a Component. Mutates the propTypes of the component * in order to validate the new variant. */ addStyle: function addStyle(Component, styleVariant) { bsStyles(styleVariant, Component); } }; var _curry = curry; exports._curry = _curry; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$assign = __webpack_require__(10)["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; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(11), __esModule: true }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(12); module.exports = __webpack_require__(15).Object.assign; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(13); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(18)}); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(14) , core = __webpack_require__(15) , ctx = __webpack_require__(16) , 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; /***/ }, /* 14 */ /***/ 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 /***/ }, /* 15 */ /***/ function(module, exports) { var core = module.exports = {version: '1.2.6'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(17); 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); }; }; /***/ }, /* 17 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.1 Object.assign(target, source, ...) var $ = __webpack_require__(19) , toObject = __webpack_require__(20) , IObject = __webpack_require__(22); // should work with symbols and should have deterministic property order (V8 bug) module.exports = __webpack_require__(24)(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; /***/ }, /* 19 */ /***/ 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 }; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(21); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 21 */ /***/ 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; }; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(23); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 23 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 24 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _Object$assign = __webpack_require__(10)['default']; var _Object$create = __webpack_require__(26)['default']; var _Object$keys = __webpack_require__(28)['default']; exports.__esModule = true; var constant = function constant(obj) { return _Object$assign(_Object$create({ values: function values() { var _this = this; return _Object$keys(this).map(function (k) { return _this[k]; }); } }), obj); }; var styleMaps = { SIZES: { 'large': 'lg', 'medium': 'md', 'small': 'sm', 'xsmall': 'xs', 'lg': 'lg', 'md': 'md', 'sm': 'sm', 'xs': 'xs' }, GRID_COLUMNS: 12 }; var Sizes = constant({ LARGE: 'large', MEDIUM: 'medium', SMALL: 'small', XSMALL: 'xsmall' }); exports.Sizes = Sizes; var State = constant({ SUCCESS: 'success', WARNING: 'warning', DANGER: 'danger', INFO: 'info' }); exports.State = State; var DEFAULT = 'default'; exports.DEFAULT = DEFAULT; var PRIMARY = 'primary'; exports.PRIMARY = PRIMARY; var LINK = 'link'; exports.LINK = LINK; var INVERSE = 'inverse'; exports.INVERSE = INVERSE; exports['default'] = styleMaps; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(27), __esModule: true }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(19); module.exports = function create(P, D){ return $.create(P, D); }; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(29), __esModule: true }; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(30); module.exports = __webpack_require__(15).Object.keys; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(20); __webpack_require__(31)('keys', function($keys){ return function keys(it){ return $keys(toObject(it)); }; }); /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(13) , core = __webpack_require__(15) , fails = __webpack_require__(24); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; /***/ }, /* 32 */ /***/ 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; /***/ }, /* 33 */ /***/ 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; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _PanelGroup = __webpack_require__(35); var _PanelGroup2 = _interopRequireDefault(_PanelGroup); var Accordion = _react2['default'].createClass({ displayName: 'Accordion', render: function render() { return _react2['default'].createElement( _PanelGroup2['default'], _extends({}, this.props, { accordion: true }), this.props.children ); } }); exports['default'] = Accordion; module.exports = exports['default']; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var PanelGroup = _react2['default'].createClass({ displayName: 'PanelGroup', propTypes: { accordion: _react2['default'].PropTypes.bool, activeKey: _react2['default'].PropTypes.any, className: _react2['default'].PropTypes.string, children: _react2['default'].PropTypes.node, defaultActiveKey: _react2['default'].PropTypes.any, onSelect: _react2['default'].PropTypes.func }, getDefaultProps: function getDefaultProps() { return { accordion: false }; }, getInitialState: function getInitialState() { var defaultActiveKey = this.props.defaultActiveKey; return { activeKey: defaultActiveKey }; }, render: function render() { var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); if (this.props.accordion) { props.role = 'tablist'; } return _react2['default'].createElement( 'div', _extends({}, props, { className: _classnames2['default'](className, classes), onSelect: null }), _utilsValidComponentChildren2['default'].map(props.children, this.renderPanel) ); }, renderPanel: function renderPanel(child, index) { var activeKey = this.props.activeKey != null ? this.props.activeKey : this.state.activeKey; var props = { bsStyle: child.props.bsStyle || this.props.bsStyle, key: child.key ? child.key : index, ref: child.ref }; if (this.props.accordion) { props.headerRole = 'tab'; props.panelRole = 'tabpanel'; props.collapsible = true; props.expanded = child.props.eventKey === activeKey; props.onSelect = this.handleSelect; } return _react.cloneElement(child, props); }, shouldComponentUpdate: function shouldComponentUpdate() { // Defer any updates to this component during the `onSelect` handler. return !this._isChanging; }, handleSelect: function handleSelect(e, key) { e.preventDefault(); if (this.props.onSelect) { this._isChanging = true; this.props.onSelect(key); this._isChanging = false; } if (this.state.activeKey === key) { key = null; } this.setState({ activeKey: key }); } }); exports['default'] = _utilsBootstrapUtils.bsClass('panel-group', PanelGroup); module.exports = exports['default']; /***/ }, /* 36 */ /***/ 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; /***/ }, /* 37 */ /***/ 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; } }()); /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibDeprecated = __webpack_require__(39); var _reactPropTypesLibDeprecated2 = _interopRequireDefault(_reactPropTypesLibDeprecated); var _styleMaps = __webpack_require__(25); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var Alert = _react2['default'].createClass({ displayName: 'Alert', propTypes: { onDismiss: _react2['default'].PropTypes.func, dismissAfter: _reactPropTypesLibDeprecated2['default'](_react2['default'].PropTypes.number, 'No longer supported.'), closeLabel: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { closeLabel: 'Close Alert' }; }, renderDismissButton: function renderDismissButton() { return _react2['default'].createElement( 'button', { type: 'button', className: 'close', onClick: this.props.onDismiss, 'aria-hidden': 'true', tabIndex: '-1' }, _react2['default'].createElement( 'span', null, '×' ) ); }, renderSrOnlyDismissButton: function renderSrOnlyDismissButton() { return _react2['default'].createElement( 'button', { type: 'button', className: 'close sr-only', onClick: this.props.onDismiss }, this.props.closeLabel ); }, render: function render() { var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); var isDismissable = !!this.props.onDismiss; classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'dismissable')] = isDismissable; return _react2['default'].createElement( 'div', _extends({}, this.props, { role: 'alert', className: _classnames2['default'](this.props.className, classes) }), isDismissable ? this.renderDismissButton() : null, this.props.children, isDismissable ? this.renderSrOnlyDismissButton() : null ); }, componentDidMount: function componentDidMount() { if (this.props.dismissAfter && this.props.onDismiss) { this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter); } }, componentWillUnmount: function componentWillUnmount() { clearTimeout(this.dismissTimer); } }); exports['default'] = _utilsBootstrapUtils.bsStyles(_styleMaps.State.values(), _styleMaps.State.INFO, _utilsBootstrapUtils.bsClass('alert', Alert)); module.exports = exports['default']; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = deprecated; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _warning = __webpack_require__(33); var _warning2 = _interopRequireDefault(_warning); function deprecated(propType, explanation) { return function validate(props, propName, componentName) { if (props[propName] != null) { _warning2['default'](false, '"' + propName + '" property of "' + componentName + '" has been deprecated.\n' + explanation); } return propType(props, propName, componentName); }; } module.exports = exports['default']; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var Badge = _react2['default'].createClass({ displayName: 'Badge', propTypes: { pullRight: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { pullRight: false, bsClass: 'badge' }; }, hasContent: function hasContent() { return _utilsValidComponentChildren2['default'].hasValidComponent(this.props.children) || _react2['default'].Children.count(this.props.children) > 1 || typeof this.props.children === 'string' || typeof this.props.children === 'number'; }, render: function render() { var _classes; var classes = (_classes = { 'pull-right': this.props.pullRight }, _classes[_utilsBootstrapUtils2['default'].prefix(this.props)] = this.hasContent(), _classes); return _react2['default'].createElement( 'span', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.children ); } }); exports['default'] = Badge; module.exports = exports['default']; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var Breadcrumb = _react2['default'].createClass({ displayName: 'Breadcrumb', propTypes: { /** * bootstrap className * @private */ bsClass: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { bsClass: 'breadcrumb' }; }, render: function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); return _react2['default'].createElement( 'ol', _extends({}, props, { role: 'navigation', 'aria-label': 'breadcrumbs', className: _classnames2['default'](className, this.props.bsClass) }), _utilsValidComponentChildren2['default'].map(this.props.children, this.renderBreadcrumbItem) ); }, renderBreadcrumbItem: function renderBreadcrumbItem(child, index) { return _react.cloneElement(child, { key: child.key || index }); } }); exports['default'] = Breadcrumb; module.exports = exports['default']; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _SafeAnchor = __webpack_require__(43); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var BreadcrumbItem = _react2['default'].createClass({ displayName: 'BreadcrumbItem', propTypes: { /** * If set to true, renders `span` instead of `a` */ active: _react2['default'].PropTypes.bool, /** * HTML id for the wrapper `li` element */ id: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]), /** * HTML id for the inner `a` element */ linkId: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]), /** * `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 }, getDefaultProps: function getDefaultProps() { return { active: false }; }, render: function render() { var _props = this.props; var active = _props.active; var className = _props.className; var id = _props.id; var linkId = _props.linkId; var children = _props.children; var href = _props.href; var title = _props.title; var target = _props.target; var props = _objectWithoutProperties(_props, ['active', 'className', 'id', 'linkId', 'children', 'href', 'title', 'target']); var linkProps = { href: href, title: title, target: target, id: linkId }; return _react2['default'].createElement( 'li', { id: id, className: _classnames2['default'](className, { active: active }) }, active ? _react2['default'].createElement( 'span', props, children ) : _react2['default'].createElement( _SafeAnchor2['default'], _extends({}, props, linkProps), children ) ); } }); exports['default'] = BreadcrumbItem; module.exports = exports['default']; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); /** * Note: This is intended as a stop-gap for accessibility concerns that the * Bootstrap CSS does not address as they have styled anchors and not buttons * in many cases. */ var SafeAnchor = (function (_React$Component) { _inherits(SafeAnchor, _React$Component); function SafeAnchor(props) { _classCallCheck(this, SafeAnchor); _React$Component.call(this, props); this.handleClick = this.handleClick.bind(this); } SafeAnchor.prototype.handleClick = function handleClick(event) { if (this.props.href === undefined) { event.preventDefault(); } }; SafeAnchor.prototype.render = function render() { return _react2['default'].createElement('a', _extends({ role: this.props.href ? undefined : 'button' }, this.props, { onClick: _utilsCreateChainedFunction2['default'](this.props.onClick, this.handleClick), href: this.props.href || '' })); }; return SafeAnchor; })(_react2['default'].Component); exports['default'] = SafeAnchor; SafeAnchor.propTypes = { href: _react2['default'].PropTypes.string, onClick: _react2['default'].PropTypes.func }; module.exports = exports['default']; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$create = __webpack_require__(26)["default"]; var _Object$setPrototypeOf = __webpack_require__(45)["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; /***/ }, /* 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__(15).Object.setPrototypeOf; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(13); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(48).set}); /***/ }, /* 48 */ /***/ 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__(19).getDesc , isObject = __webpack_require__(49) , anObject = __webpack_require__(50); 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__(16)(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 }; /***/ }, /* 49 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(49); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 51 */ /***/ 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; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); var types = ['button', 'reset', 'submit']; var ButtonStyles = _styleMaps.State.values().concat(_styleMaps.DEFAULT, _styleMaps.PRIMARY, _styleMaps.LINK); var Button = _react2['default'].createClass({ displayName: 'Button', propTypes: { active: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, block: _react2['default'].PropTypes.bool, navItem: _react2['default'].PropTypes.bool, navDropdown: _react2['default'].PropTypes.bool, /** * You can use a custom element for this component */ componentClass: _reactPropTypesLibElementType2['default'], href: _react2['default'].PropTypes.string, target: _react2['default'].PropTypes.string, /** * Defines HTML button type Attribute * @type {("button"|"reset"|"submit")} * @defaultValue 'button' */ type: _react2['default'].PropTypes.oneOf(types) }, getDefaultProps: function getDefaultProps() { return { active: false, block: false, disabled: false, navItem: false, navDropdown: false }; }, render: function render() { var _extends2; var classes = this.props.navDropdown ? {} : _utilsBootstrapUtils2['default'].getClassSet(this.props); var renderFuncName = undefined; var blockClass = _utilsBootstrapUtils2['default'].prefix(this.props, 'block'); classes = _extends((_extends2 = { active: this.props.active }, _extends2[blockClass] = this.props.block, _extends2), classes); if (this.props.navItem) { return this.renderNavItem(classes); } renderFuncName = this.props.href || this.props.target || this.props.navDropdown ? 'renderAnchor' : 'renderButton'; return this[renderFuncName](classes); }, renderAnchor: function renderAnchor(classes) { var Component = this.props.componentClass || 'a'; var href = this.props.href || '#'; classes.disabled = this.props.disabled; return _react2['default'].createElement( Component, _extends({}, this.props, { href: href, className: _classnames2['default'](this.props.className, classes), role: 'button' }), this.props.children ); }, renderButton: function renderButton(classes) { var Component = this.props.componentClass || 'button'; return _react2['default'].createElement( Component, _extends({}, this.props, { type: this.props.type || 'button', className: _classnames2['default'](this.props.className, classes) }), this.props.children ); }, renderNavItem: function renderNavItem(classes) { var liClasses = { active: this.props.active }; return _react2['default'].createElement( 'li', { className: _classnames2['default'](liClasses) }, this.renderAnchor(classes) ); } }); Button.types = types; exports['default'] = _utilsBootstrapUtils.bsStyles(ButtonStyles, _styleMaps.DEFAULT, _utilsBootstrapUtils.bsSizes([_styleMaps.Sizes.LARGE, _styleMaps.Sizes.SMALL, _styleMaps.Sizes.XSMALL], _utilsBootstrapUtils.bsClass('btn', Button))); module.exports = exports['default']; /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _common = __webpack_require__(54); /** * 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']; /***/ }, /* 54 */ /***/ 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; } /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _reactPropTypesLibAll = __webpack_require__(56); var _reactPropTypesLibAll2 = _interopRequireDefault(_reactPropTypesLibAll); var _Button = __webpack_require__(52); var _Button2 = _interopRequireDefault(_Button); var ButtonGroup = _react2['default'].createClass({ displayName: 'ButtonGroup', 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 (props) { if (props.block && !props.vertical) { return new Error('The block property requires the vertical property to be set to have any effect'); } }) }, getDefaultProps: function getDefaultProps() { return { block: false, justified: false, vertical: false }; }, render: function render() { var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); classes[_utilsBootstrapUtils2['default'].prefix(this.props)] = !this.props.vertical; classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'vertical')] = this.props.vertical; classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'justified')] = this.props.justified; // this is annoying, since the class is `btn-block` not `btn-group-block` classes[_utilsBootstrapUtils2['default'].prefix(_Button2['default'].defaultProps, 'block')] = this.props.block; return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.children ); } }); exports['default'] = _utilsBootstrapUtils.bsClass('btn-group', ButtonGroup); module.exports = exports['default']; /***/ }, /* 56 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = all; 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'); } return 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; } } }; } module.exports = exports['default']; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Button = __webpack_require__(52); var _Button2 = _interopRequireDefault(_Button); var _FormGroup = __webpack_require__(58); var _FormGroup2 = _interopRequireDefault(_FormGroup); var _InputBase2 = __webpack_require__(59); var _InputBase3 = _interopRequireDefault(_InputBase2); var _utilsChildrenValueInputValidation = __webpack_require__(3); var _utilsChildrenValueInputValidation2 = _interopRequireDefault(_utilsChildrenValueInputValidation); var ButtonInput = (function (_InputBase) { _inherits(ButtonInput, _InputBase); function ButtonInput() { _classCallCheck(this, ButtonInput); _InputBase.apply(this, arguments); } ButtonInput.prototype.renderFormGroup = function renderFormGroup(children) { var _props = this.props; var bsStyle = _props.bsStyle; var value = _props.value; var other = _objectWithoutProperties(_props, ['bsStyle', 'value']); return _react2['default'].createElement( _FormGroup2['default'], other, children ); }; ButtonInput.prototype.renderInput = function renderInput() { var _props2 = this.props; var children = _props2.children; var value = _props2.value; var other = _objectWithoutProperties(_props2, ['children', 'value']); var val = children ? children : value; return _react2['default'].createElement(_Button2['default'], _extends({}, other, { componentClass: 'input', ref: 'input', key: 'input', value: val })); }; return ButtonInput; })(_InputBase3['default']); ButtonInput.types = _Button2['default'].types; ButtonInput.defaultProps = { type: 'button' }; ButtonInput.propTypes = { type: _react2['default'].PropTypes.oneOf(ButtonInput.types), bsStyle: function bsStyle() { // defer to Button propTypes of bsStyle return null; }, children: _utilsChildrenValueInputValidation2['default'], value: _utilsChildrenValueInputValidation2['default'] }; exports['default'] = ButtonInput; module.exports = exports['default']; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var FormGroup = (function (_React$Component) { _inherits(FormGroup, _React$Component); function FormGroup() { _classCallCheck(this, FormGroup); _React$Component.apply(this, arguments); } FormGroup.prototype.render = function render() { var classes = { 'form-group': !this.props.standalone, 'form-group-lg': !this.props.standalone && this.props.bsSize === 'large', 'form-group-sm': !this.props.standalone && this.props.bsSize === 'small', 'has-feedback': this.props.hasFeedback, 'has-success': this.props.bsStyle === 'success', 'has-warning': this.props.bsStyle === 'warning', 'has-error': this.props.bsStyle === 'error' }; return _react2['default'].createElement( 'div', { className: _classnames2['default'](classes, this.props.groupClassName) }, this.props.children ); }; return FormGroup; })(_react2['default'].Component); FormGroup.defaultProps = { hasFeedback: false, standalone: false }; FormGroup.propTypes = { standalone: _react2['default'].PropTypes.bool, hasFeedback: _react2['default'].PropTypes.bool, bsSize: function bsSize(props) { if (props.standalone && props.bsSize !== undefined) { return new Error('bsSize will not be used when `standalone` is set.'); } return _react2['default'].PropTypes.oneOf(['small', 'medium', 'large']).apply(null, arguments); }, bsStyle: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']), groupClassName: _react2['default'].PropTypes.string }; exports['default'] = FormGroup; module.exports = exports['default']; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _FormGroup = __webpack_require__(58); var _FormGroup2 = _interopRequireDefault(_FormGroup); var _Glyphicon = __webpack_require__(60); var _Glyphicon2 = _interopRequireDefault(_Glyphicon); var InputBase = (function (_React$Component) { _inherits(InputBase, _React$Component); function InputBase() { _classCallCheck(this, InputBase); _React$Component.apply(this, arguments); } InputBase.prototype.getInputDOMNode = function getInputDOMNode() { return this.refs.input; }; InputBase.prototype.getValue = function getValue() { if (this.props.type === 'static') { return this.props.value; } else if (this.props.type) { if (this.props.type === 'select' && this.props.multiple) { return this.getSelectedOptions(); } return this.getInputDOMNode().value; } throw new Error('Cannot use getValue without specifying input type.'); }; InputBase.prototype.getChecked = function getChecked() { return this.getInputDOMNode().checked; }; InputBase.prototype.getSelectedOptions = function getSelectedOptions() { var values = []; Array.prototype.forEach.call(this.getInputDOMNode().getElementsByTagName('option'), function (option) { if (option.selected) { var value = option.getAttribute('value') || option.innerHtml; values.push(value); } }); return values; }; InputBase.prototype.isCheckboxOrRadio = function isCheckboxOrRadio() { return this.props.type === 'checkbox' || this.props.type === 'radio'; }; InputBase.prototype.isFile = function isFile() { return this.props.type === 'file'; }; InputBase.prototype.renderInputGroup = function renderInputGroup(children) { var addonBefore = this.props.addonBefore ? _react2['default'].createElement( 'span', { className: 'input-group-addon', key: 'addonBefore' }, this.props.addonBefore ) : null; var addonAfter = this.props.addonAfter ? _react2['default'].createElement( 'span', { className: 'input-group-addon', key: 'addonAfter' }, this.props.addonAfter ) : null; var buttonBefore = this.props.buttonBefore ? _react2['default'].createElement( 'span', { className: 'input-group-btn' }, this.props.buttonBefore ) : null; var buttonAfter = this.props.buttonAfter ? _react2['default'].createElement( 'span', { className: 'input-group-btn' }, this.props.buttonAfter ) : null; var inputGroupClassName = undefined; switch (this.props.bsSize) { case 'small': inputGroupClassName = 'input-group-sm';break; case 'large': inputGroupClassName = 'input-group-lg';break; default: } return addonBefore || addonAfter || buttonBefore || buttonAfter ? _react2['default'].createElement( 'div', { className: _classnames2['default'](inputGroupClassName, 'input-group'), key: 'input-group' }, addonBefore, buttonBefore, children, addonAfter, buttonAfter ) : children; }; InputBase.prototype.renderIcon = function renderIcon() { if (this.props.hasFeedback) { if (this.props.feedbackIcon) { return _react2['default'].cloneElement(this.props.feedbackIcon, { formControlFeedback: true }); } switch (this.props.bsStyle) { case 'success': return _react2['default'].createElement(_Glyphicon2['default'], { formControlFeedback: true, glyph: 'ok', key: 'icon' }); case 'warning': return _react2['default'].createElement(_Glyphicon2['default'], { formControlFeedback: true, glyph: 'warning-sign', key: 'icon' }); case 'error': return _react2['default'].createElement(_Glyphicon2['default'], { formControlFeedback: true, glyph: 'remove', key: 'icon' }); default: return _react2['default'].createElement('span', { className: 'form-control-feedback', key: 'icon' }); } } else { return null; } }; InputBase.prototype.renderHelp = function renderHelp() { return this.props.help ? _react2['default'].createElement( 'span', { className: 'help-block', key: 'help' }, this.props.help ) : null; }; InputBase.prototype.renderCheckboxAndRadioWrapper = function renderCheckboxAndRadioWrapper(children) { var classes = { 'checkbox': this.props.type === 'checkbox', 'radio': this.props.type === 'radio' }; return _react2['default'].createElement( 'div', { className: _classnames2['default'](classes), key: 'checkboxRadioWrapper' }, children ); }; InputBase.prototype.renderWrapper = function renderWrapper(children) { return this.props.wrapperClassName ? _react2['default'].createElement( 'div', { className: this.props.wrapperClassName, key: 'wrapper' }, children ) : children; }; InputBase.prototype.renderLabel = function renderLabel(children) { var classes = { 'control-label': !this.isCheckboxOrRadio() }; classes[this.props.labelClassName] = this.props.labelClassName; return this.props.label ? _react2['default'].createElement( 'label', { htmlFor: this.props.id, className: _classnames2['default'](classes), key: 'label' }, children, this.props.label ) : children; }; InputBase.prototype.renderInput = function renderInput() { if (!this.props.type) { return this.props.children; } switch (this.props.type) { case 'select': return _react2['default'].createElement( 'select', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'form-control'), ref: 'input', key: 'input' }), this.props.children ); case 'textarea': return _react2['default'].createElement('textarea', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'form-control'), ref: 'input', key: 'input' })); case 'static': return _react2['default'].createElement( 'p', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'form-control-static'), ref: 'input', key: 'input' }), this.props.value ); default: var className = this.isCheckboxOrRadio() || this.isFile() ? '' : 'form-control'; return _react2['default'].createElement('input', _extends({}, this.props, { className: _classnames2['default'](this.props.className, className), ref: 'input', key: 'input' })); } }; InputBase.prototype.renderFormGroup = function renderFormGroup(children) { return _react2['default'].createElement( _FormGroup2['default'], this.props, children ); }; InputBase.prototype.renderChildren = function renderChildren() { return !this.isCheckboxOrRadio() ? [this.renderLabel(), this.renderWrapper([this.renderInputGroup(this.renderInput()), this.renderIcon(), this.renderHelp()])] : this.renderWrapper([this.renderCheckboxAndRadioWrapper(this.renderLabel(this.renderInput())), this.renderHelp()]); }; InputBase.prototype.render = function render() { var children = this.renderChildren(); return this.renderFormGroup(children); }; return InputBase; })(_react2['default'].Component); InputBase.propTypes = { type: _react2['default'].PropTypes.string, label: _react2['default'].PropTypes.node, help: _react2['default'].PropTypes.node, addonBefore: _react2['default'].PropTypes.node, addonAfter: _react2['default'].PropTypes.node, buttonBefore: _react2['default'].PropTypes.node, buttonAfter: _react2['default'].PropTypes.node, bsSize: _react2['default'].PropTypes.oneOf(['small', 'medium', 'large']), bsStyle: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']), hasFeedback: _react2['default'].PropTypes.bool, feedbackIcon: _react2['default'].PropTypes.node, id: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]), groupClassName: _react2['default'].PropTypes.string, wrapperClassName: _react2['default'].PropTypes.string, labelClassName: _react2['default'].PropTypes.string, multiple: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, value: _react2['default'].PropTypes.any }; InputBase.defaultProps = { disabled: false, hasFeedback: false, multiple: false }; exports['default'] = InputBase; module.exports = exports['default']; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var Glyphicon = _react2['default'].createClass({ displayName: 'Glyphicon', propTypes: { /** * bootstrap className * @private */ bsClass: _react2['default'].PropTypes.string, /** * An icon name. See e.g. http://getbootstrap.com/components/#glyphicons */ glyph: _react2['default'].PropTypes.string.isRequired, /** * Adds 'form-control-feedback' class * @private */ formControlFeedback: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { bsClass: 'glyphicon', formControlFeedback: false }; }, render: function render() { var _classNames; var className = _classnames2['default'](this.props.className, (_classNames = {}, _classNames[this.props.bsClass] = true, _classNames['glyphicon-' + this.props.glyph] = true, _classNames['form-control-feedback'] = this.props.formControlFeedback, _classNames)); return _react2['default'].createElement( 'span', _extends({}, this.props, { className: className }), this.props.children ); } }); exports['default'] = Glyphicon; module.exports = exports['default']; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _Button = __webpack_require__(52); var _Button2 = _interopRequireDefault(_Button); var ButtonToolbar = _react2['default'].createClass({ displayName: 'ButtonToolbar', propTypes: { bsSize: _Button2['default'].propTypes.bsSize }, getDefaultProps: function getDefaultProps() { return { bsClass: 'btn-toolbar' }; }, render: function render() { var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); return _react2['default'].createElement( 'div', _extends({}, this.props, { role: 'toolbar', className: _classnames2['default'](this.props.className, classes) }), this.props.children ); } }); exports['default'] = ButtonToolbar; module.exports = exports['default']; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _Glyphicon = __webpack_require__(60); var _Glyphicon2 = _interopRequireDefault(_Glyphicon); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var Carousel = _react2['default'].createClass({ displayName: 'Carousel', 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, 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 }, getDefaultProps: function getDefaultProps() { return { bsClass: 'carousel', 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' }) }; }, getInitialState: function getInitialState() { return { activeIndex: this.props.defaultActiveIndex == null ? 0 : this.props.defaultActiveIndex, previousActiveIndex: null, direction: null }; }, getDirection: function getDirection(prevIndex, index) { if (prevIndex === index) { return null; } return prevIndex > index ? 'prev' : 'next'; }, 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) }); } }, componentDidMount: function componentDidMount() { this.waitForNext(); }, componentWillUnmount: function componentWillUnmount() { clearTimeout(this.timeout); }, next: function next(e) { if (e) { e.preventDefault(); } var index = this.getActiveIndex() + 1; var count = _utilsValidComponentChildren2['default'].numberOf(this.props.children); if (index > count - 1) { if (!this.props.wrap) { return; } index = 0; } this.handleSelect(index, 'next'); }, prev: function prev(e) { if (e) { e.preventDefault(); } var index = this.getActiveIndex() - 1; if (index < 0) { if (!this.props.wrap) { return; } index = _utilsValidComponentChildren2['default'].numberOf(this.props.children) - 1; } this.handleSelect(index, 'prev'); }, pause: function pause() { this.isPaused = true; clearTimeout(this.timeout); }, play: function play() { this.isPaused = false; this.waitForNext(); }, waitForNext: function waitForNext() { if (!this.isPaused && this.props.slide && this.props.interval && this.props.activeIndex == null) { this.timeout = setTimeout(this.next, this.props.interval); } }, handleMouseOver: function handleMouseOver() { if (this.props.pauseOnHover) { this.pause(); } }, handleMouseOut: function handleMouseOut() { if (this.isPaused) { this.play(); } }, render: function render() { var _classes; var classes = (_classes = {}, _classes[_utilsBootstrapUtils2['default'].prefix(this.props)] = true, _classes.slide = this.props.slide, _classes); return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes), onMouseOver: this.handleMouseOver, onMouseOut: this.handleMouseOut }), this.props.indicators ? this.renderIndicators() : null, _react2['default'].createElement( 'div', { ref: 'inner', className: _utilsBootstrapUtils2['default'].prefix(this.props, 'inner') }, _utilsValidComponentChildren2['default'].map(this.props.children, this.renderItem) ), this.props.controls ? this.renderControls() : null ); }, renderPrev: function renderPrev() { var classes = 'left ' + _utilsBootstrapUtils2['default'].prefix(this.props, 'control'); return _react2['default'].createElement( 'a', { className: classes, href: '#prev', key: 0, onClick: this.prev }, this.props.prevIcon ); }, renderNext: function renderNext() { var classes = 'right ' + _utilsBootstrapUtils2['default'].prefix(this.props, 'control'); return _react2['default'].createElement( 'a', { className: classes, href: '#next', key: 1, onClick: this.next }, this.props.nextIcon ); }, renderControls: function renderControls() { if (!this.props.wrap) { var activeIndex = this.getActiveIndex(); var count = _utilsValidComponentChildren2['default'].numberOf(this.props.children); return [activeIndex !== 0 ? this.renderPrev() : null, activeIndex !== count - 1 ? this.renderNext() : null]; } return [this.renderPrev(), this.renderNext()]; }, renderIndicator: function renderIndicator(child, index) { var className = index === this.getActiveIndex() ? 'active' : null; return _react2['default'].createElement('li', { key: index, className: className, onClick: this.handleSelect.bind(this, index, null) }); }, renderIndicators: function renderIndicators() { var _this = this; var indicators = []; _utilsValidComponentChildren2['default'].forEach(this.props.children, function (child, index) { indicators.push(_this.renderIndicator(child, index), // Force whitespace between indicator elements, bootstrap // requires this for correct spacing of elements. ' '); }, this); return _react2['default'].createElement( 'ol', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'indicators') }, indicators ); }, getActiveIndex: function getActiveIndex() { return this.props.activeIndex != null ? this.props.activeIndex : this.state.activeIndex; }, handleItemAnimateOutEnd: function handleItemAnimateOutEnd() { var _this2 = this; this.setState({ previousActiveIndex: null, direction: null }, function () { _this2.waitForNext(); if (_this2.props.onSlideEnd) { _this2.props.onSlideEnd(); } }); }, renderItem: function renderItem(child, index) { var activeIndex = this.getActiveIndex(); var isActive = index === activeIndex; var isPreviousActive = this.state.previousActiveIndex != null && this.state.previousActiveIndex === index && this.props.slide; return _react.cloneElement(child, { active: isActive, ref: child.ref, key: child.key ? child.key : index, index: index, animateOut: isPreviousActive, animateIn: isActive && this.state.previousActiveIndex != null && this.props.slide, direction: this.state.direction, onAnimateOutEnd: isPreviousActive ? this.handleItemAnimateOutEnd : null }); }, handleSelect: function handleSelect(index, direction) { clearTimeout(this.timeout); if (this.isMounted()) { var previousActiveIndex = this.getActiveIndex(); direction = direction || this.getDirection(previousActiveIndex, index); if (this.props.onSelect) { this.props.onSelect(index, direction); } if (this.props.activeIndex == null && index !== previousActiveIndex) { if (this.state.previousActiveIndex != null) { // If currently animating don't activate the new index. // TODO: look into queuing this canceled call and // animating after the current animation has ended. return; } this.setState({ activeIndex: index, previousActiveIndex: previousActiveIndex, direction: direction }); } } } }); exports['default'] = Carousel; module.exports = exports['default']; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _utilsTransitionEvents = __webpack_require__(65); var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var CarouselItem = _react2['default'].createClass({ displayName: 'CarouselItem', 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, caption: _react2['default'].PropTypes.node, index: _react2['default'].PropTypes.number }, getInitialState: function getInitialState() { return { direction: null }; }, getDefaultProps: function getDefaultProps() { return { bsStyle: 'carousel', active: false, animateIn: false, animateOut: false }; }, handleAnimateOutEnd: function handleAnimateOutEnd() { if (this.props.onAnimateOutEnd && this.isMounted()) { this.props.onAnimateOutEnd(this.props.index); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }, componentDidUpdate: function componentDidUpdate(prevProps) { if (!this.props.active && prevProps.active) { _utilsTransitionEvents2['default'].addEndEventListener(_reactDom2['default'].findDOMNode(this), this.handleAnimateOutEnd); } if (this.props.active !== prevProps.active) { setTimeout(this.startAnimation, 20); } }, startAnimation: function startAnimation() { if (!this.isMounted()) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }, render: function render() { var classes = { item: true, active: this.props.active && !this.props.animateIn || this.props.animateOut, next: this.props.active && this.props.animateIn && this.props.direction === 'next', prev: this.props.active && this.props.animateIn && this.props.direction === 'prev' }; if (this.state.direction && (this.props.animateIn || this.props.animateOut)) { classes[this.state.direction] = true; } return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.children, this.props.caption ? this.renderCaption() : null ); }, renderCaption: function renderCaption() { var classes = _utilsBootstrapUtils2['default'].prefix(this.props, 'caption'); return _react2['default'].createElement( 'div', { className: classes }, this.props.caption ); } }); exports['default'] = CarouselItem; module.exports = exports['default']; /***/ }, /* 64 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_64__; /***/ }, /* 65 */ /***/ 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']; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _Object$keys = __webpack_require__(28)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _styleMaps = __webpack_require__(25); var _styleMaps2 = _interopRequireDefault(_styleMaps); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var Col = _react2['default'].createClass({ displayName: 'Col', propTypes: { /** * 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, /** * You can use a custom element for this component */ componentClass: _reactPropTypesLibElementType2['default'] }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, render: function render() { var _this = this; var ComponentClass = this.props.componentClass; var classes = {}; _Object$keys(_styleMaps2['default'].SIZES).forEach(function (key) { var size = _styleMaps2['default'].SIZES[key]; var prop = size; var classPart = size + '-'; if (_this.props[prop]) { classes['col-' + classPart + _this.props[prop]] = true; } classes['hidden-' + size] = _this.props[size + 'Hidden']; 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 _react2['default'].createElement( ComponentClass, _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.children ); } }); exports['default'] = Col; module.exports = exports['default']; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Collapse = __webpack_require__(68); var _Collapse2 = _interopRequireDefault(_Collapse); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsDeprecationWarning = __webpack_require__(81); var _utilsDeprecationWarning2 = _interopRequireDefault(_utilsDeprecationWarning); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var CollapsibleNav = _react2['default'].createClass({ displayName: 'CollapsibleNav', propTypes: { onSelect: _react2['default'].PropTypes.func, activeHref: _react2['default'].PropTypes.string, activeKey: _react2['default'].PropTypes.any, collapsible: _react2['default'].PropTypes.bool, expanded: _react2['default'].PropTypes.bool, eventKey: _react2['default'].PropTypes.any }, getDefaultProps: function getDefaultProps() { return { collapsible: false, expanded: false }; }, render: function render() { /* * this.props.collapsible is set in NavBar when an eventKey is supplied. */ var classes = this.props.collapsible ? 'navbar-collapse' : null; var renderChildren = this.props.collapsible ? this.renderCollapsibleNavChildren : this.renderChildren; var nav = _react2['default'].createElement( 'div', { eventKey: this.props.eventKey, className: _classnames2['default'](this.props.className, classes) }, _utilsValidComponentChildren2['default'].map(this.props.children, renderChildren) ); if (this.props.collapsible) { return _react2['default'].createElement( _Collapse2['default'], { 'in': this.props.expanded }, nav ); } return nav; }, getChildActiveProp: function getChildActiveProp(child) { if (child.props.active) { return true; } if (this.props.activeKey != null) { if (child.props.eventKey === this.props.activeKey) { return true; } } if (this.props.activeHref != null) { if (child.props.href === this.props.activeHref) { return true; } } return child.props.active; }, renderChildren: function renderChildren(child, index) { var key = child.key ? child.key : index; return _react.cloneElement(child, { activeKey: this.props.activeKey, activeHref: this.props.activeHref, ref: 'nocollapse_' + key, key: key, navItem: true }); }, renderCollapsibleNavChildren: function renderCollapsibleNavChildren(child, index) { var key = child.key ? child.key : index; return _react.cloneElement(child, { active: this.getChildActiveProp(child), activeKey: this.props.activeKey, activeHref: this.props.activeHref, onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, this.props.onSelect), ref: 'collapsible_' + key, key: key, navItem: true }); } }); exports['default'] = _utilsDeprecationWarning2['default'].wrapper(CollapsibleNav, 'CollapsibleNav', 'Navbar.Collapse', 'http://react-bootstrap.github.io/components.html#navbars'); module.exports = exports['default']; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _domHelpersStyle = __webpack_require__(69); var _domHelpersStyle2 = _interopRequireDefault(_domHelpersStyle); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _reactOverlaysLibTransition = __webpack_require__(77); var _reactOverlaysLibTransition2 = _interopRequireDefault(_reactOverlaysLibTransition); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var capitalize = function capitalize(str) { return str[0].toUpperCase() + str.substr(1); }; // reading a dimension prop will cause the browser to recalculate, // which will let our animations work var triggerBrowserReflow = function triggerBrowserReflow(node) { return node.offsetHeight; }; var MARGINS = { height: ['marginTop', 'marginBottom'], width: ['marginLeft', 'marginRight'] }; function getDimensionValue(dimension, elem) { var value = elem['offset' + capitalize(dimension)]; var margins = MARGINS[dimension]; return value + parseInt(_domHelpersStyle2['default'](elem, margins[0]), 10) + parseInt(_domHelpersStyle2['default'](elem, margins[1]), 10); } var Collapse = (function (_React$Component) { _inherits(Collapse, _React$Component); function Collapse(props, context) { _classCallCheck(this, Collapse); _React$Component.call(this, props, context); this.onEnterListener = this.handleEnter.bind(this); this.onEnteringListener = this.handleEntering.bind(this); this.onEnteredListener = this.handleEntered.bind(this); this.onExitListener = this.handleExit.bind(this); this.onExitingListener = this.handleExiting.bind(this); } // Explicitly copied from Transition for doc generation. // TODO: Remove duplication once #977 is resolved. Collapse.prototype.render = function render() { var enter = _utilsCreateChainedFunction2['default'](this.onEnterListener, this.props.onEnter); var entering = _utilsCreateChainedFunction2['default'](this.onEnteringListener, this.props.onEntering); var entered = _utilsCreateChainedFunction2['default'](this.onEnteredListener, this.props.onEntered); var exit = _utilsCreateChainedFunction2['default'](this.onExitListener, this.props.onExit); var exiting = _utilsCreateChainedFunction2['default'](this.onExitingListener, this.props.onExiting); return _react2['default'].createElement( _reactOverlaysLibTransition2['default'], _extends({ ref: 'transition' }, this.props, { 'aria-expanded': this.props.role ? this.props['in'] : null, className: _classnames2['default'](this.props.className, { width: this._dimension() === 'width' }), exitedClassName: 'collapse', exitingClassName: 'collapsing', enteredClassName: 'collapse in', enteringClassName: 'collapsing', onEnter: enter, onEntering: entering, onEntered: entered, onExit: exit, onExiting: exiting, onExited: this.props.onExited }), this.props.children ); }; /* -- 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' + capitalize(dimension)] + 'px'; }; return Collapse; })(_react2['default'].Component); Collapse.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 }; Collapse.defaultProps = { 'in': false, timeout: 300, unmountOnExit: false, transitionAppear: false, dimension: 'height', getDimensionValue: getDimensionValue }; exports['default'] = Collapse; module.exports = exports['default']; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var camelize = __webpack_require__(70), hyphenate = __webpack_require__(72), _getComputedStyle = __webpack_require__(74), removeStyle = __webpack_require__(76); 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; }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js */ 'use strict'; var camelize = __webpack_require__(71); var msPattern = /^-ms-/; module.exports = function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); }; /***/ }, /* 71 */ /***/ function(module, exports) { "use strict"; var rHyphen = /-(.)/g; module.exports = function camelize(string) { return string.replace(rHyphen, function (_, chr) { return chr.toUpperCase(); }); }; /***/ }, /* 72 */ /***/ 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__(73); var msPattern = /^ms-/; module.exports = function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, "-ms-"); }; /***/ }, /* 73 */ /***/ function(module, exports) { 'use strict'; var rUpper = /([A-Z])/g; module.exports = function hyphenate(string) { return string.replace(rUpper, '-$1').toLowerCase(); }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(75); var _utilCamelizeStyle = __webpack_require__(70); var _utilCamelizeStyle2 = babelHelpers.interopRequireDefault(_utilCamelizeStyle); var rposition = /^(top|right|bottom|left)$/; var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i; module.exports = function _getComputedStyle(node) { if (!node) throw new TypeError('No Element passed to `getComputedStyle()`'); var doc = node.ownerDocument; return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : { //ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72 getPropertyValue: function getPropertyValue(prop) { var style = node.style; prop = (0, _utilCamelizeStyle2['default'])(prop); if (prop == 'float') prop = 'styleFloat'; var current = node.currentStyle[prop] || null; if (current == null && style && style[prop]) current = style[prop]; if (rnumnonpx.test(current) && !rposition.test(prop)) { // Remember the original values var left = style.left; var runStyle = node.runtimeStyle; var rsLeft = runStyle && runStyle.left; // Put in the new values to get a computed value out if (rsLeft) runStyle.left = node.currentStyle.left; style.left = prop === 'fontSize' ? '1em' : current; current = style.pixelLeft + 'px'; // Revert the changed values style.left = left; if (rsLeft) runStyle.left = rsLeft; } return current; } }; }; /***/ }, /* 75 */ /***/ 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; }; }) /***/ }, /* 76 */ /***/ function(module, exports) { 'use strict'; module.exports = function removeStyle(node, key) { return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key); }; /***/ }, /* 77 */ /***/ 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; }; 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 _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _domHelpersTransitionProperties = __webpack_require__(78); var _domHelpersTransitionProperties2 = _interopRequireDefault(_domHelpersTransitionProperties); var _domHelpersEventsOn = __webpack_require__(80); var _domHelpersEventsOn2 = _interopRequireDefault(_domHelpersEventsOn); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var transitionEndEvent = _domHelpersTransitionProperties2['default'].end; var UNMOUNTED = 0; exports.UNMOUNTED = UNMOUNTED; var EXITED = 1; exports.EXITED = EXITED; var ENTERING = 2; exports.ENTERING = ENTERING; var ENTERED = 3; exports.ENTERED = ENTERED; var EXITING = 4; exports.EXITING = EXITING; /** * 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); _React$Component.call(this, props, context); var initialStatus = undefined; 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; } Transition.prototype.componentDidMount = function componentDidMount() { if (this.props.transitionAppear && this.props['in']) { this.performEnter(this.props); } }; Transition.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var status = this.state.status; if (nextProps['in']) { if (status === EXITING) { this.performEnter(nextProps); } else if (this.props.unmountOnExit) { if (status === UNMOUNTED) { // Start enter transition in componentDidUpdate. this.setState({ status: EXITED }); } } else if (status === EXITED) { this.performEnter(nextProps); } // Otherwise we're already entering or entered. } else { if (status === ENTERING || status === ENTERED) { this.performExit(nextProps); } // Otherwise we're already exited or exiting. } }; Transition.prototype.componentDidUpdate = function componentDidUpdate() { if (this.props.unmountOnExit && this.state.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 }); } } }; Transition.prototype.componentWillUnmount = function componentWillUnmount() { this.cancelNextCallback(); }; Transition.prototype.performEnter = function performEnter(props) { var _this = 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 () { _this.props.onEntering(node); _this.onTransitionEnd(node, function () { _this.safeSetState({ status: ENTERED }, function () { _this.props.onEntered(node); }); }); }); }; Transition.prototype.performExit = function performExit(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.onExit(node); this.safeSetState({ status: EXITING }, function () { _this2.props.onExiting(node); _this2.onTransitionEnd(node, function () { _this2.safeSetState({ status: EXITED }, function () { _this2.props.onExited(node); }); }); }); }; Transition.prototype.cancelNextCallback = function cancelNextCallback() { if (this.nextCallback !== null) { this.nextCallback.cancel(); this.nextCallback = null; } }; Transition.prototype.safeSetState = 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)); }; Transition.prototype.setNextCallback = function setNextCallback(callback) { var _this3 = this; var active = true; this.nextCallback = function (event) { if (active) { active = false; _this3.nextCallback = null; callback(event); } }; this.nextCallback.cancel = function () { active = false; }; return this.nextCallback; }; Transition.prototype.onTransitionEnd = function onTransitionEnd(node, handler) { this.setNextCallback(handler); if (node) { _domHelpersEventsOn2['default'](node, transitionEndEvent, this.nextCallback); setTimeout(this.nextCallback, this.props.timeout); } else { setTimeout(this.nextCallback, 0); } }; Transition.prototype.render = 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 = undefined; 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: _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; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(79); 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 }; } /***/ }, /* 79 */ /***/ function(module, exports) { 'use strict'; module.exports = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(79); 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; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _warning = __webpack_require__(33); 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; module.exports = exports['default']; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _domHelpersActiveElement = __webpack_require__(83); var _domHelpersActiveElement2 = _interopRequireDefault(_domHelpersActiveElement); var _domHelpersQueryContains = __webpack_require__(85); var _domHelpersQueryContains2 = _interopRequireDefault(_domHelpersQueryContains); var _keycode = __webpack_require__(86); var _keycode2 = _interopRequireDefault(_keycode); var _lodashCompatCollectionFind = __webpack_require__(87); var _lodashCompatCollectionFind2 = _interopRequireDefault(_lodashCompatCollectionFind); var _lodashCompatObjectOmit = __webpack_require__(140); var _lodashCompatObjectOmit2 = _interopRequireDefault(_lodashCompatObjectOmit); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactPropTypesLibAll = __webpack_require__(56); var _reactPropTypesLibAll2 = _interopRequireDefault(_reactPropTypesLibAll); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _reactPropTypesLibIsRequiredForA11y = __webpack_require__(155); var _reactPropTypesLibIsRequiredForA11y2 = _interopRequireDefault(_reactPropTypesLibIsRequiredForA11y); var _uncontrollable = __webpack_require__(156); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _ButtonGroup = __webpack_require__(55); var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); var _DropdownMenu = __webpack_require__(159); var _DropdownMenu2 = _interopRequireDefault(_DropdownMenu); var _DropdownToggle = __webpack_require__(165); var _DropdownToggle2 = _interopRequireDefault(_DropdownToggle); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsCustomPropTypes = __webpack_require__(166); var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var TOGGLE_REF = 'toggle-btn'; var TOGGLE_ROLE = _DropdownToggle2['default'].defaultProps.bsRole; var MENU_ROLE = _DropdownMenu2['default'].defaultProps.bsRole; var Dropdown = (function (_React$Component) { _inherits(Dropdown, _React$Component); function Dropdown(props) { _classCallCheck(this, Dropdown); _React$Component.call(this, props); this.Toggle = _DropdownToggle2['default']; this.toggleOpen = this.toggleOpen.bind(this); this.handleClick = this.handleClick.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.handleClose = this.handleClose.bind(this); this.extractChildren = this.extractChildren.bind(this); this.refineMenu = this.refineMenu.bind(this); this.refineToggle = this.refineToggle.bind(this); this.childExtractors = [{ key: 'toggle', matches: function matches(child) { return child.props.bsRole === TOGGLE_ROLE; }, refine: this.refineToggle }, { key: 'menu', exclusive: true, matches: function matches(child) { return child.props.bsRole === MENU_ROLE; }, refine: this.refineMenu }]; this.state = {}; 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.refs.menu), _domHelpersActiveElement2['default'](document)); } }; Dropdown.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { if (this.props.open && !prevProps.open) { this.focusNextOnOpen(); } if (!this.props.open && prevProps.open) { // 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.render = function render() { var _rootClasses; var children = this.extractChildren(); var Component = this.props.componentClass; var props = _lodashCompatObjectOmit2['default'](this.props, ['id', 'bsClass', 'role']); var className = _utilsBootstrapUtils2['default'].prefix(this.props); var rootClasses = (_rootClasses = { open: this.props.open, disabled: this.props.disabled }, _rootClasses[className] = !this.props.dropup, _rootClasses.dropup = this.props.dropup, _rootClasses); return _react2['default'].createElement( Component, _extends({}, props, { className: _classnames2['default'](this.props.className, rootClasses) }), children ); }; Dropdown.prototype.toggleOpen = function toggleOpen() { var eventType = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0]; var open = !this.props.open; if (open) { this.lastOpenEventType = eventType; } if (this.props.onToggle) { this.props.onToggle(open); } }; 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.refs.menu.focusNext) { this.refs.menu.focusNext(); } event.preventDefault(); break; case _keycode2['default'].codes.esc: case _keycode2['default'].codes.tab: this.handleClose(event); break; default: } }; Dropdown.prototype.handleClose = function handleClose() { if (!this.props.open) { return; } this.toggleOpen(); }; Dropdown.prototype.focusNextOnOpen = function focusNextOnOpen() { var menu = this.refs.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.refs[TOGGLE_REF]); if (toggle && toggle.focus) { toggle.focus(); } }; Dropdown.prototype.extractChildren = function extractChildren() { var _this = this; var open = !!this.props.open; var seen = {}; return _utilsValidComponentChildren2['default'].map(this.props.children, function (child) { var extractor = _lodashCompatCollectionFind2['default'](_this.childExtractors, function (x) { return x.matches(child); }); if (extractor) { if (seen[extractor.key]) { return false; } seen[extractor.key] = extractor.exclusive; child = extractor.refine(child, open); } return child; }); }; Dropdown.prototype.refineMenu = function refineMenu(menu, open) { var menuProps = { ref: 'menu', open: open, labelledBy: this.props.id, pullRight: this.props.pullRight, bsClass: this.props.bsClass }; menuProps.onClose = _utilsCreateChainedFunction2['default'](menu.props.onClose, this.props.onClose, this.handleClose); menuProps.onSelect = _utilsCreateChainedFunction2['default'](menu.props.onSelect, this.props.onSelect, this.handleClose); return _react.cloneElement(menu, menuProps, menu.props.children); }; Dropdown.prototype.refineToggle = function refineToggle(toggle, open) { var toggleProps = { open: open, id: this.props.id, ref: TOGGLE_REF, role: this.props.role }; toggleProps.onClick = _utilsCreateChainedFunction2['default'](toggle.props.onClick, this.handleClick); toggleProps.onKeyDown = _utilsCreateChainedFunction2['default'](toggle.props.onKeyDown, this.handleKeyDown); return _react.cloneElement(toggle, toggleProps, toggle.props.children); }; return Dropdown; })(_react2['default'].Component); Dropdown.Toggle = _DropdownToggle2['default']; Dropdown.TOGGLE_REF = TOGGLE_REF; Dropdown.TOGGLE_ROLE = TOGGLE_ROLE; Dropdown.MENU_ROLE = MENU_ROLE; Dropdown.defaultProps = { componentClass: _ButtonGroup2['default'], bsClass: 'dropdown' }; Dropdown.propTypes = { bsClass: _react2['default'].PropTypes.string, /** * 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'](_utilsCustomPropTypes2['default'].requiredRoles(TOGGLE_ROLE, MENU_ROLE), _utilsCustomPropTypes2['default'].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 * function(Object event, Any eventKey) * ``` */ 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 }; Dropdown = _uncontrollable2['default'](Dropdown, { open: 'onToggle' }); Dropdown.Toggle = _DropdownToggle2['default']; Dropdown.Menu = _DropdownMenu2['default']; exports['default'] = Dropdown; module.exports = exports['default']; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(75); exports.__esModule = true; /** * document.activeElement */ exports['default'] = activeElement; var _ownerDocument = __webpack_require__(84); 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']; /***/ }, /* 84 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = ownerDocument; function ownerDocument(node) { return node && node.ownerDocument || document; } module.exports = exports["default"]; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(79); 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; /***/ }, /* 86 */ /***/ 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, 'right click': 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': 33, '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] } /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(88), createFind = __webpack_require__(113); /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is bound to `thisArg` and * invoked with three arguments: (value, index|key, collection). * * If a property name is provided for `predicate` the created `_.property` * style callback returns the property value of the given element. * * If a value is also provided for `thisArg` the created `_.matchesProperty` * style callback returns `true` for elements that have a matching property * value, else `false`. * * If an object is provided for `predicate` the created `_.matches` style * callback returns `true` for elements that have the properties of the given * object, else `false`. * * @static * @memberOf _ * @alias detect * @category Collection * @param {Array|Object|string} collection The collection to search. * @param {Function|Object|string} [predicate=_.identity] The function invoked * per iteration. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.result(_.find(users, function(chr) { * return chr.age < 40; * }), 'user'); * // => 'barney' * * // using the `_.matches` callback shorthand * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); * // => 'pebbles' * * // using the `_.matchesProperty` callback shorthand * _.result(_.find(users, 'active', false), 'user'); * // => 'fred' * * // using the `_.property` callback shorthand * _.result(_.find(users, 'active'), 'user'); * // => 'barney' */ var find = createFind(baseEach); module.exports = find; /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(89), createBaseEach = __webpack_require__(112); /** * The base implementation of `_.forEach` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(90), keys = __webpack_require__(97); /** * The base implementation of `_.forOwn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(91); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var toObject = __webpack_require__(92); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(93), isString = __webpack_require__(94), support = __webpack_require__(96); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { if (support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); } module.exports = toObject; /***/ }, /* 93 */ /***/ function(module, exports) { /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { var isObjectLike = __webpack_require__(95); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } module.exports = isString; /***/ }, /* 95 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 96 */ /***/ function(module, exports) { /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, objectProto = Object.prototype; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default (IE < 9, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly set the `[[Enumerable]]` value of a function's `prototype` * property to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an object's own properties, shadowing non-enumerable ones, * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects * correctly. * * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array * `shift()` and `splice()` functions that fail to remove the last element, * `value[0]`, of array-like objects even though the "length" property is * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, * while `splice()` is buggy regardless of mode in IE < 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index. IE 8 can only access characters * by index on string literals, not string objects. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; }(1, 0)); module.exports = support; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(98), isArrayLike = __webpack_require__(102), isObject = __webpack_require__(93), shimKeys = __webpack_require__(106), support = __webpack_require__(96); /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { var isNative = __webpack_require__(99); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(100), isHostObject = __webpack_require__(101), isObjectLike = __webpack_require__(95); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } module.exports = isNative; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(93); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 which returns 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } module.exports = isFunction; /***/ }, /* 101 */ /***/ function(module, exports) { /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { // IE < 9 presents many host objects as `Object` objects that can coerce // to strings despite having improperly defined `toString` methods. return typeof value.toString != 'function' && typeof (value + '') == 'string'; }; }()); module.exports = isHostObject; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { var getLength = __webpack_require__(103), isLength = __webpack_require__(105); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } module.exports = isArrayLike; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(104); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var toObject = __webpack_require__(92); /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : toObject(object)[key]; }; } module.exports = baseProperty; /***/ }, /* 105 */ /***/ function(module, exports) { /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { var isArguments = __webpack_require__(107), isArray = __webpack_require__(108), isIndex = __webpack_require__(109), isLength = __webpack_require__(105), isString = __webpack_require__(94), keysIn = __webpack_require__(110); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(102), isObjectLike = __webpack_require__(95); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); } module.exports = isArguments; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(98), isLength = __webpack_require__(105), isObjectLike = __webpack_require__(95); /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; module.exports = isArray; /***/ }, /* 109 */ /***/ function(module, exports) { /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(111), isArguments = __webpack_require__(107), isArray = __webpack_require__(108), isFunction = __webpack_require__(100), isIndex = __webpack_require__(109), isLength = __webpack_require__(105), isObject = __webpack_require__(93), isString = __webpack_require__(94), support = __webpack_require__(96); /** `Object#toString` result references. */ var arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** Used to fix the JScript `[[DontEnum]]` bug. */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used for native method references. */ var errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to avoid iterating over non-enumerable properties in IE < 9. */ var nonEnumProps = {}; nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; nonEnumProps[objectTag] = { 'constructor': true }; arrayEach(shadowProps, function(key) { for (var tag in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, tag)) { var props = nonEnumProps[tag]; props[key] = hasOwnProperty.call(props, key); } } }); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)) && length) || 0; var Ctor = object.constructor, index = -1, proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, isProto = proto === object, result = Array(length), skipIndexes = length > 0, skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), skipProto = support.enumPrototypes && isFunction(object); while (++index < length) { result[index] = (index + ''); } // lodash skips the `constructor` property when it infers it's iterating // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` // attribute of an existing property and the `constructor` property of a // prototype defaults to non-enumerable. for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name')) && !(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; if (tag == objectTag) { proto = objectProto; } length = shadowProps.length; while (length--) { key = shadowProps[length]; var nonEnum = nonEnums[key]; if (!(isProto && nonEnum) && (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { result.push(key); } } } return result; } module.exports = keysIn; /***/ }, /* 111 */ /***/ function(module, exports) { /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { var getLength = __webpack_require__(103), isLength = __webpack_require__(105), toObject = __webpack_require__(92); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { var baseCallback = __webpack_require__(114), baseFind = __webpack_require__(138), baseFindIndex = __webpack_require__(139), isArray = __webpack_require__(108); /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new find function. */ function createFind(eachFunc, fromRight) { return function(collection, predicate, thisArg) { predicate = baseCallback(predicate, thisArg, 3); if (isArray(collection)) { var index = baseFindIndex(collection, predicate, fromRight); return index > -1 ? collection[index] : undefined; } return baseFind(collection, predicate, eachFunc); }; } module.exports = createFind; /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(115), baseMatchesProperty = __webpack_require__(127), bindCallback = __webpack_require__(134), identity = __webpack_require__(135), property = __webpack_require__(136); /** * The base implementation of `_.callback` which supports specifying the * number of arguments to provide to `func`. * * @private * @param {*} [func=_.identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } module.exports = baseCallback; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(116), getMatchData = __webpack_require__(124), toObject = __webpack_require__(92); /** * The base implementation of `_.matches` which does not clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { var key = matchData[0][0], value = matchData[0][1]; return function(object) { if (object == null) { return false; } object = toObject(object); return object[key] === value && (value !== undefined || (key in object)); }; } return function(object) { return baseIsMatch(object, matchData); }; } module.exports = baseMatches; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(117), toObject = __webpack_require__(92); /** * The base implementation of `_.isMatch` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to inspect. * @param {Array} matchData The propery names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparing objects. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = toObject(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var result = customizer ? customizer(objValue, srcValue, key) : undefined; if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(118), isObject = __webpack_require__(93), isObjectLike = __webpack_require__(95); /** * The base implementation of `_.isEqual` without support for `this` binding * `customizer` functions. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } module.exports = baseIsEqual; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { var equalArrays = __webpack_require__(119), equalByTag = __webpack_require__(121), equalObjects = __webpack_require__(122), isArray = __webpack_require__(108), isHostObject = __webpack_require__(101), isTypedArray = __webpack_require__(123); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing objects. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `value` objects. * @param {Array} [stackB=[]] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } // Assume cyclic values are equal. // For more information on detecting circular references see https://es5.github.io/#JO. stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } // Add `object` and `other` to the stack of traversed objects. stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } module.exports = baseIsEqualDeep; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { var arraySome = __webpack_require__(120); /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing arrays. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index], result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; if (result !== undefined) { if (result) { continue; } return false; } // Recursively compare arrays (susceptible to call stack limits). if (isLoose) { if (!arraySome(other, function(othValue) { return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); })) { return false; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { return false; } } return true; } module.exports = equalArrays; /***/ }, /* 120 */ /***/ function(module, exports) { /** * A specialized version of `_.some` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }, /* 121 */ /***/ function(module, exports) { /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', numberTag = '[object Number]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: // 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 +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: // Treat `NaN` vs. `NaN` as equal. return (object != +object) ? other != +other : object == +other; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings primitives and string // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. return object == (other + ''); } return false; } module.exports = equalByTag; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { var keys = __webpack_require__(97); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Function} [customizer] The function to customize comparing values. * @param {boolean} [isLoose] Specify performing partial comparisons. * @param {Array} [stackA] Tracks traversed `value` objects. * @param {Array} [stackB] Tracks traversed `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { return false; } } var skipCtor = isLoose; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key], result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; // Recursively compare objects (susceptible to call stack limits). if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } module.exports = equalObjects; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { var isLength = __webpack_require__(105), isObjectLike = __webpack_require__(95); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(125), pairs = __webpack_require__(126); /** * Gets the propery names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = pairs(object), length = result.length; while (length--) { result[length][2] = isStrictComparable(result[length][1]); } return result; } module.exports = getMatchData; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(93); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { var keys = __webpack_require__(97), toObject = __webpack_require__(92); /** * Creates a two dimensional array of the key-value pairs for `object`, * e.g. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) */ function pairs(object) { object = toObject(object); var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } module.exports = pairs; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(128), baseIsEqual = __webpack_require__(117), baseSlice = __webpack_require__(129), isArray = __webpack_require__(108), isKey = __webpack_require__(130), isStrictComparable = __webpack_require__(125), last = __webpack_require__(131), toObject = __webpack_require__(92), toPath = __webpack_require__(132); /** * The base implementation of `_.matchesProperty` which does not clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to compare. * @returns {Function} Returns the new function. */ function baseMatchesProperty(path, srcValue) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(srcValue), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === srcValue ? (srcValue !== undefined || (key in object)) : baseIsEqual(srcValue, object[key], undefined, true); }; } module.exports = baseMatchesProperty; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { var toObject = __webpack_require__(92); /** * The base implementation of `get` without support for string paths * and default values. * * @private * @param {Object} object The object to query. * @param {Array} path The path of the property to get. * @param {string} [pathKey] The key representation of path. * @returns {*} Returns the resolved value. */ function baseGet(object, path, pathKey) { if (object == null) { return; } object = toObject(object); if (pathKey !== undefined && pathKey in object) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = toObject(object)[path[index++]]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }, /* 129 */ /***/ function(module, exports) { /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } module.exports = baseSlice; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(108), toObject = __webpack_require__(92); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } module.exports = isKey; /***/ }, /* 131 */ /***/ function(module, exports) { /** * Gets the last element of `array`. * * @static * @memberOf _ * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } module.exports = last; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(133), isArray = __webpack_require__(108); /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `value` to property path array if it's not one. * * @private * @param {*} value The value to process. * @returns {Array} Returns the property path array. */ function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } module.exports = toPath; /***/ }, /* 133 */ /***/ function(module, exports) { /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { return value == null ? '' : (value + ''); } module.exports = baseToString; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(135); /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } module.exports = bindCallback; /***/ }, /* 135 */ /***/ function(module, exports) { /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(104), basePropertyDeep = __webpack_require__(137), isKey = __webpack_require__(130); /** * Creates a function that returns the property value at `path` on a * given object. * * @static * @memberOf _ * @category Utility * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. * @example * * var objects = [ * { 'a': { 'b': { 'c': 2 } } }, * { 'a': { 'b': { 'c': 1 } } } * ]; * * _.map(objects, _.property('a.b.c')); * // => [2, 1] * * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } module.exports = property; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(128), toPath = __webpack_require__(132); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new function. */ function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } module.exports = basePropertyDeep; /***/ }, /* 138 */ /***/ function(module, exports) { /** * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`, * without support for callback shorthands and `this` binding, which iterates * over `collection` using the provided `eachFunc`. * * @private * @param {Array|Object|string} collection The collection to search. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @param {boolean} [retKey] Specify returning the key of the found element * instead of the element itself. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFind(collection, predicate, eachFunc, retKey) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = retKey ? key : value; return false; } }); return result; } module.exports = baseFind; /***/ }, /* 139 */ /***/ function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for callback shorthands and `this` binding. * * @private * @param {Array} array The array to search. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(141), baseDifference = __webpack_require__(142), baseFlatten = __webpack_require__(149), bindCallback = __webpack_require__(134), keysIn = __webpack_require__(110), pickByArray = __webpack_require__(151), pickByCallback = __webpack_require__(152), restParam = __webpack_require__(154); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable properties of `object` that are not omitted. * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|...(string|string[])} [predicate] The function invoked per * iteration or property names to omit, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Object} Returns the new object. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.omit(object, 'age'); * // => { 'user': 'fred' } * * _.omit(object, _.isNumber); * // => { 'user': 'fred' } */ var omit = restParam(function(object, props) { if (object == null) { return {}; } if (typeof props[0] != 'function') { var props = arrayMap(baseFlatten(props), String); return pickByArray(object, baseDifference(keysIn(object), props)); } var predicate = bindCallback(props[0], props[1], 3); return pickByCallback(object, function(value, key, object) { return !predicate(value, key, object); }); }); module.exports = omit; /***/ }, /* 141 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(143), cacheIndexOf = __webpack_require__(145), createCache = __webpack_require__(146); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of `_.difference` which accepts a single array * of values to exclude. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values) { var length = array ? array.length : 0, result = []; if (!length) { return result; } var index = -1, indexOf = baseIndexOf, isCommon = true, cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null, valuesLength = values.length; if (cache) { indexOf = cacheIndexOf; isCommon = false; values = cache; } outer: while (++index < length) { var value = array[index]; if (isCommon && value === value) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === value) { continue outer; } } result.push(value); } else if (indexOf(values, value, 0) < 0) { result.push(value); } } return result; } module.exports = baseDifference; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { var indexOfNaN = __webpack_require__(144); /** * The base implementation of `_.indexOf` without support for binary searches. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { if (value !== value) { return indexOfNaN(array, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = baseIndexOf; /***/ }, /* 144 */ /***/ function(module, exports) { /** * Gets the index at which the first occurrence of `NaN` is found in `array`. * * @private * @param {Array} array The array to search. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched `NaN`, else `-1`. */ function indexOfNaN(array, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 0 : -1); while ((fromRight ? index-- : ++index < length)) { var other = array[index]; if (other !== other) { return index; } } return -1; } module.exports = indexOfNaN; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(93); /** * Checks if `value` is in `cache` mimicking the return signature of * `_.indexOf` by returning `0` if the value is found, else `-1`. * * @private * @param {Object} cache The cache to search. * @param {*} value The value to search for. * @returns {number} Returns `0` if `value` is found, else `-1`. */ function cacheIndexOf(cache, value) { var data = cache.data, result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; return result ? 0 : -1; } module.exports = cacheIndexOf; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var SetCache = __webpack_require__(147), getNative = __webpack_require__(98); /** Native method references. */ var Set = getNative(global, 'Set'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeCreate = getNative(Object, 'create'); /** * Creates a `Set` cache object to optimize linear searches of large arrays. * * @private * @param {Array} [values] The values to cache. * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. */ function createCache(values) { return (nativeCreate && Set) ? new SetCache(values) : null; } module.exports = createCache; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var cachePush = __webpack_require__(148), getNative = __webpack_require__(98); /** Native method references. */ var Set = getNative(global, 'Set'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeCreate = getNative(Object, 'create'); /** * * Creates a cache object to store unique values. * * @private * @param {Array} [values] The values to cache. */ function SetCache(values) { var length = values ? values.length : 0; this.data = { 'hash': nativeCreate(null), 'set': new Set }; while (length--) { this.push(values[length]); } } // Add functions to the `Set` cache. SetCache.prototype.push = cachePush; module.exports = SetCache; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(93); /** * Adds `value` to the cache. * * @private * @name push * @memberOf SetCache * @param {*} value The value to cache. */ function cachePush(value) { var data = this.data; if (typeof value == 'string' || isObject(value)) { data.set.add(value); } else { data.hash[value] = true; } } module.exports = cachePush; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(150), isArguments = __webpack_require__(107), isArray = __webpack_require__(108), isArrayLike = __webpack_require__(102), isObjectLike = __webpack_require__(95); /** * The base implementation of `_.flatten` with added support for restricting * flattening and specifying the start index. * * @private * @param {Array} array The array to flatten. * @param {boolean} [isDeep] Specify a deep flatten. * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, isDeep, isStrict, result) { result || (result = []); var index = -1, length = array.length; while (++index < length) { var value = array[index]; if (isObjectLike(value) && isArrayLike(value) && (isStrict || isArray(value) || isArguments(value))) { if (isDeep) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, isDeep, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 150 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { var toObject = __webpack_require__(92); /** * A specialized version of `_.pick` which picks `object` properties specified * by `props`. * * @private * @param {Object} object The source object. * @param {string[]} props The property names to pick. * @returns {Object} Returns the new object. */ function pickByArray(object, props) { object = toObject(object); var index = -1, length = props.length, result = {}; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } return result; } module.exports = pickByArray; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { var baseForIn = __webpack_require__(153); /** * A specialized version of `_.pick` which picks `object` properties `predicate` * returns truthy for. * * @private * @param {Object} object The source object. * @param {Function} predicate The function invoked per iteration. * @returns {Object} Returns the new object. */ function pickByCallback(object, predicate) { var result = {}; baseForIn(object, function(value, key, object) { if (predicate(value, key, object)) { result[key] = value; } }); return result; } module.exports = pickByCallback; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(90), keysIn = __webpack_require__(110); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } module.exports = baseForIn; /***/ }, /* 154 */ /***/ function(module, exports) { /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; /***/ }, /* 155 */ /***/ 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"]; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _createUncontrollable = __webpack_require__(157); var _createUncontrollable2 = _interopRequireDefault(_createUncontrollable); 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'] = _createUncontrollable2['default']([mixin], set); module.exports = exports['default']; /***/ }, /* 157 */ /***/ 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; 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 _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(158); var utils = _interopRequireWildcard(_utils); 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, propTypes; propTypes = utils.uncontrolledPropTypes(controlledValues, basePropTypes, displayName); 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 props = this.props, keys = Object.keys(controlledValues); this._values = utils.transform(keys, function (values, key) { 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 _this = this; var props = this.props, keys = Object.keys(controlledValues); keys.forEach(function (key) { if (utils.getValue(nextProps, key) === undefined && utils.getValue(props, key) !== undefined) { _this._values[key] = nextProps[utils.defaultKey(key)]; } }); }, render: function render() { var _this2 = this; var newProps = {}; var _props = this.props; var valueLink = _props.valueLink; var checkedLink = _props.checkedLink; var props = _objectWithoutProperties(_props, ['valueLink', 'checkedLink']); utils.each(controlledValues, function (handle, propName) { var linkPropName = utils.getLinkName(propName), prop = _this2.props[propName]; if (linkPropName && !isProp(_this2.props, propName) && isProp(_this2.props, linkPropName)) { prop = _this2.props[linkPropName].value; } newProps[propName] = prop !== undefined ? prop : _this2._values[propName]; newProps[handle] = setAndNotify.bind(_this2, propName); }); newProps = _extends({}, props, newProps, { ref: 'inner' }); return _react2['default'].createElement(Component, newProps); } })); component.ControlledComponent = Component; /** * useful when wrapping a Component and you want to control * everything */ component.deferControlTo = function (newComponent, additions, nextMethods) { if (additions === undefined) additions = {}; 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; } } } module.exports = exports['default']; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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.has = has; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(32); var _invariant2 = _interopRequireDefault(_invariant); 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]; _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 = _react2['default'].version.split('.').map(parseFloat); exports.version = version; function getType(component) { if (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); } function has(o, k) { return o ? Object.prototype.hasOwnProperty.call(o, k) : false; } /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _keycode = __webpack_require__(86); var _keycode2 = _interopRequireDefault(_keycode); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _reactOverlaysLibRootCloseWrapper = __webpack_require__(160); var _reactOverlaysLibRootCloseWrapper2 = _interopRequireDefault(_reactOverlaysLibRootCloseWrapper); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var DropdownMenu = (function (_React$Component) { _inherits(DropdownMenu, _React$Component); function DropdownMenu(props) { _classCallCheck(this, DropdownMenu); _React$Component.call(this, props); this.focusNext = this.focusNext.bind(this); this.focusPrevious = this.focusPrevious.bind(this); this.getFocusableMenuItems = this.getFocusableMenuItems.bind(this); this.getItemsAndActiveIndex = this.getItemsAndActiveIndex.bind(this); 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.focusNext = function focusNext() { var _getItemsAndActiveIndex = this.getItemsAndActiveIndex(); var items = _getItemsAndActiveIndex.items; var activeItemIndex = _getItemsAndActiveIndex.activeItemIndex; if (items.length === 0) { return; } if (activeItemIndex === items.length - 1) { items[0].focus(); return; } items[activeItemIndex + 1].focus(); }; DropdownMenu.prototype.focusPrevious = function focusPrevious() { var _getItemsAndActiveIndex2 = this.getItemsAndActiveIndex(); var items = _getItemsAndActiveIndex2.items; var activeItemIndex = _getItemsAndActiveIndex2.activeItemIndex; if (activeItemIndex === 0) { items[items.length - 1].focus(); return; } items[activeItemIndex - 1].focus(); }; DropdownMenu.prototype.getItemsAndActiveIndex = function getItemsAndActiveIndex() { var items = this.getFocusableMenuItems(); var activeElement = document.activeElement; var activeItemIndex = items.indexOf(activeElement); return { items: items, activeItemIndex: activeItemIndex }; }; DropdownMenu.prototype.getFocusableMenuItems = function getFocusableMenuItems() { var menuNode = _reactDom2['default'].findDOMNode(this); if (menuNode === undefined) { return []; } return [].slice.call(menuNode.querySelectorAll('[tabIndex="-1"]'), 0); }; DropdownMenu.prototype.render = function render() { var _classes, _this = this; var _props = this.props; var children = _props.children; var onSelect = _props.onSelect; var pullRight = _props.pullRight; var className = _props.className; var labelledBy = _props.labelledBy; var open = _props.open; var onClose = _props.onClose; var props = _objectWithoutProperties(_props, ['children', 'onSelect', 'pullRight', 'className', 'labelledBy', 'open', 'onClose']); var items = _utilsValidComponentChildren2['default'].map(children, function (child) { var childProps = child.props || {}; return _react2['default'].cloneElement(child, { onKeyDown: _utilsCreateChainedFunction2['default'](childProps.onKeyDown, _this.handleKeyDown), onSelect: _utilsCreateChainedFunction2['default'](childProps.onSelect, onSelect) }, childProps.children); }); var classes = (_classes = {}, _classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'menu')] = true, _classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'menu-right')] = pullRight, _classes); var list = _react2['default'].createElement( 'ul', _extends({ className: _classnames2['default'](className, classes), role: 'menu', 'aria-labelledby': labelledBy }, props), items ); if (open) { list = _react2['default'].createElement( _reactOverlaysLibRootCloseWrapper2['default'], { noWrap: true, onRootClose: onClose }, list ); } return list; }; return DropdownMenu; })(_react2['default'].Component); DropdownMenu.defaultProps = { bsRole: 'menu', bsClass: 'dropdown', pullRight: false }; DropdownMenu.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 }; exports['default'] = DropdownMenu; module.exports = exports['default']; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _utilsAddEventListener = __webpack_require__(161); var _utilsAddEventListener2 = _interopRequireDefault(_utilsAddEventListener); var _utilsCreateChainedFunction = __webpack_require__(163); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsOwnerDocument = __webpack_require__(164); var _utilsOwnerDocument2 = _interopRequireDefault(_utilsOwnerDocument); // TODO: Consider using an ES6 symbol here, once we use babel-runtime. var CLICK_WAS_INSIDE = '__click_was_inside'; var counter = 0; 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); _React$Component.call(this, props); this.handleDocumentClick = this.handleDocumentClick.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; } RootCloseWrapper.prototype.bindRootCloseHandlers = function bindRootCloseHandlers() { var doc = _utilsOwnerDocument2['default'](this); this._onDocumentClickListener = _utilsAddEventListener2['default'](doc, 'click', this.handleDocumentClick); this._onDocumentKeyupListener = _utilsAddEventListener2['default'](doc, 'keyup', this.handleDocumentKeyUp); }; RootCloseWrapper.prototype.handleDocumentClick = function handleDocumentClick(e) { // This is now the native event. if (e[this._suppressRootId]) { return; } this.props.onRootClose(); }; RootCloseWrapper.prototype.handleDocumentKeyUp = function handleDocumentKeyUp(e) { if (e.keyCode === 27) { this.props.onRootClose(); } }; RootCloseWrapper.prototype.unbindRootCloseHandlers = function unbindRootCloseHandlers() { if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } if (this._onDocumentKeyupListener) { this._onDocumentKeyupListener.remove(); } }; RootCloseWrapper.prototype.componentDidMount = function componentDidMount() { this.bindRootCloseHandlers(); }; RootCloseWrapper.prototype.render = function render() { var _props = this.props; var noWrap = _props.noWrap; var children = _props.children; var child = _react2['default'].Children.only(children); if (noWrap) { return _react2['default'].cloneElement(child, { onClick: _utilsCreateChainedFunction2['default'](this._suppressRootCloseHandler, child.props.onClick) }); } // 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', { onClick: this._suppressRootCloseHandler }, child ); }; RootCloseWrapper.prototype.getWrappedDOMNode = 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; }; RootCloseWrapper.prototype.componentWillUnmount = function componentWillUnmount() { this.unbindRootCloseHandlers(); }; return RootCloseWrapper; })(_react2['default'].Component); exports['default'] = RootCloseWrapper; RootCloseWrapper.displayName = 'RootCloseWrapper'; RootCloseWrapper.propTypes = { onRootClose: _react2['default'].PropTypes.func.isRequired, /** * 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 }; module.exports = exports['default']; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _domHelpersEventsOn = __webpack_require__(80); var _domHelpersEventsOn2 = _interopRequireDefault(_domHelpersEventsOn); var _domHelpersEventsOff = __webpack_require__(162); var _domHelpersEventsOff2 = _interopRequireDefault(_domHelpersEventsOff); exports['default'] = function (node, event, handler) { _domHelpersEventsOn2['default'](node, event, handler); return { remove: function remove() { _domHelpersEventsOff2['default'](node, event, handler); } }; }; module.exports = exports['default']; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(79); 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; /***/ }, /* 163 */ /***/ 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']; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _domHelpersOwnerDocument = __webpack_require__(84); var _domHelpersOwnerDocument2 = _interopRequireDefault(_domHelpersOwnerDocument); exports['default'] = function (componentOrElement) { return _domHelpersOwnerDocument2['default'](_reactDom2['default'].findDOMNode(componentOrElement)); }; module.exports = exports['default']; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _Button = __webpack_require__(52); var _Button2 = _interopRequireDefault(_Button); var _SafeAnchor = __webpack_require__(43); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var CARET = _react2['default'].createElement( 'span', null, ' ', _react2['default'].createElement('span', { className: 'caret' }) ); 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 caret = this.props.noCaret ? null : CARET; var classes = { 'dropdown-toggle': true }; var Component = this.props.useAnchor ? _SafeAnchor2['default'] : _Button2['default']; return _react2['default'].createElement( Component, _extends({}, this.props, { className: _classnames2['default'](classes, this.props.className), type: 'button', 'aria-haspopup': true, 'aria-expanded': this.props.open }), this.props.children || this.props.title, caret ); }; return DropdownToggle; })(_react2['default'].Component); exports['default'] = DropdownToggle; DropdownToggle.defaultProps = { open: false, useAnchor: false, bsRole: 'toggle' }; DropdownToggle.propTypes = { bsRole: _react2['default'].PropTypes.string, noCaret: _react2['default'].PropTypes.bool, open: _react2['default'].PropTypes.bool, title: _react2['default'].PropTypes.string, useAnchor: _react2['default'].PropTypes.bool }; DropdownToggle.isToggle = true; DropdownToggle.titleProp = 'title'; DropdownToggle.onClickProp = 'onClick'; module.exports = exports['default']; /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _reactPropTypesLibCommon = __webpack_require__(54); var _childrenToArray = __webpack_require__(167); var _childrenToArray2 = _interopRequireDefault(_childrenToArray); exports['default'] = { requiredRoles: function requiredRoles() { for (var _len = arguments.length, roles = Array(_len), _key = 0; _key < _len; _key++) { roles[_key] = arguments[_key]; } return _reactPropTypesLibCommon.createChainableTypeChecker(function requiredRolesValidator(props, propName, component) { var missing = undefined; var children = _childrenToArray2['default'](props.children); var inRole = function inRole(role, child) { return role === child.props.bsRole; }; roles.every(function (role) { if (!children.some(function (child) { return inRole(role, child); })) { 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(', '))); } }); }, exclusiveRoles: function exclusiveRoles() { for (var _len2 = arguments.length, roles = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { roles[_key2] = arguments[_key2]; } return _reactPropTypesLibCommon.createChainableTypeChecker(function exclusiveRolesValidator(props, propName, component) { var children = _childrenToArray2['default'](props.children); var duplicate = undefined; roles.every(function (role) { var childrenWithRole = children.filter(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(', '))); } }); } }; module.exports = exports['default']; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports['default'] = childrenAsArray; var _ValidComponentChildren = __webpack_require__(7); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); function childrenAsArray(children) { var result = []; if (children === undefined) { return result; } _ValidComponentChildren2['default'].forEach(children, function (child) { result.push(child); }); return result; } module.exports = exports['default']; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _Object$keys = __webpack_require__(28)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Dropdown = __webpack_require__(82); var _Dropdown2 = _interopRequireDefault(_Dropdown); var _lodashCompatObjectOmit = __webpack_require__(140); var _lodashCompatObjectOmit2 = _interopRequireDefault(_lodashCompatObjectOmit); var _lodashCompatObjectPick = __webpack_require__(169); var _lodashCompatObjectPick2 = _interopRequireDefault(_lodashCompatObjectPick); var _Button = __webpack_require__(52); var _Button2 = _interopRequireDefault(_Button); 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 bsStyle = _props.bsStyle; var bsSize = _props.bsSize; var disabled = _props.disabled; var _props2 = this.props; var title = _props2.title; var children = _props2.children; var props = _objectWithoutProperties(_props2, ['title', 'children']); var dropdownProps = _lodashCompatObjectPick2['default'](props, _Object$keys(_Dropdown2['default'].ControlledComponent.propTypes)); var toggleProps = _lodashCompatObjectOmit2['default'](props, _Object$keys(_Dropdown2['default'].ControlledComponent.propTypes)); return _react2['default'].createElement( _Dropdown2['default'], _extends({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), _react2['default'].createElement( _Dropdown2['default'].Toggle, _extends({}, toggleProps, { disabled: disabled }), title ), _react2['default'].createElement( _Dropdown2['default'].Menu, null, children ) ); }; return DropdownButton; })(_react2['default'].Component); DropdownButton.propTypes = _extends({ disabled: _react2['default'].PropTypes.bool, bsStyle: _Button2['default'].propTypes.bsStyle, bsSize: _Button2['default'].propTypes.bsSize, /** * When used with the `title` prop, the noCaret option will not render a caret icon, in the toggle element. */ noCaret: _react2['default'].PropTypes.bool, title: _react2['default'].PropTypes.node.isRequired }, _Dropdown2['default'].propTypes); DropdownButton.defaultProps = { disabled: false, pullRight: false, dropup: false, navItem: false, noCaret: false }; exports['default'] = DropdownButton; module.exports = exports['default']; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(149), bindCallback = __webpack_require__(134), pickByArray = __webpack_require__(151), pickByCallback = __webpack_require__(152), restParam = __webpack_require__(154); /** * Creates an object composed of the picked `object` properties. Property * names may be specified as individual arguments or as arrays of property * names. If `predicate` is provided it's invoked for each property of `object` * picking the properties `predicate` returns truthy for. The predicate is * bound to `thisArg` and invoked with three arguments: (value, key, object). * * @static * @memberOf _ * @category Object * @param {Object} object The source object. * @param {Function|...(string|string[])} [predicate] The function invoked per * iteration or property names to pick, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `predicate`. * @returns {Object} Returns the new object. * @example * * var object = { 'user': 'fred', 'age': 40 }; * * _.pick(object, 'user'); * // => { 'user': 'fred' } * * _.pick(object, _.isString); * // => { 'user': 'fred' } */ var pick = restParam(function(object, props) { if (object == null) { return {}; } return typeof props[0] == 'function' ? pickByCallback(object, bindCallback(props[0], props[1], 3)) : pickByArray(object, baseFlatten(props)); }); module.exports = pick; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var Grid = _react2['default'].createClass({ displayName: 'Grid', 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'] }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div', fluid: false }; }, render: function render() { var ComponentClass = this.props.componentClass; var className = this.props.fluid ? 'container-fluid' : 'container'; return _react2['default'].createElement( ComponentClass, _extends({}, this.props, { className: _classnames2['default'](this.props.className, className) }), this.props.children ); } }); exports['default'] = Grid; module.exports = exports['default']; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var Image = _react2['default'].createClass({ displayName: 'Image', 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 }, getDefaultProps: function getDefaultProps() { return { responsive: false, rounded: false, circle: false, thumbnail: false }; }, render: function render() { var classes = { 'img-responsive': this.props.responsive, 'img-rounded': this.props.rounded, 'img-circle': this.props.circle, 'img-thumbnail': this.props.thumbnail }; return _react2['default'].createElement('img', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) })); } }); exports['default'] = Image; module.exports = exports['default']; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; var _interopRequireWildcard = __webpack_require__(2)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _InputBase2 = __webpack_require__(59); var _InputBase3 = _interopRequireDefault(_InputBase2); var _FormControls = __webpack_require__(173); var FormControls = _interopRequireWildcard(_FormControls); var _utilsDeprecationWarning = __webpack_require__(81); var _utilsDeprecationWarning2 = _interopRequireDefault(_utilsDeprecationWarning); var Input = (function (_InputBase) { _inherits(Input, _InputBase); function Input() { _classCallCheck(this, Input); _InputBase.apply(this, arguments); } Input.prototype.render = function render() { if (this.props.type === 'static') { _utilsDeprecationWarning2['default']('Input type=static', 'FormControls.Static'); return _react2['default'].createElement(FormControls.Static, this.props); } return _InputBase.prototype.render.call(this); }; return Input; })(_InputBase3['default']); Input.propTypes = { type: _react2['default'].PropTypes.string }; exports['default'] = Input; module.exports = exports['default']; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _Static2 = __webpack_require__(174); var _Static3 = _interopRequireDefault(_Static2); exports.Static = _Static3['default']; /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _InputBase2 = __webpack_require__(59); var _InputBase3 = _interopRequireDefault(_InputBase2); var _utilsChildrenValueInputValidation = __webpack_require__(3); var _utilsChildrenValueInputValidation2 = _interopRequireDefault(_utilsChildrenValueInputValidation); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var Static = (function (_InputBase) { _inherits(Static, _InputBase); function Static() { _classCallCheck(this, Static); _InputBase.apply(this, arguments); } Static.prototype.getValue = function getValue() { var _props = this.props; var children = _props.children; var value = _props.value; return children ? children : value; }; Static.prototype.renderInput = function renderInput() { var _props2 = this.props; var ComponentClass = _props2.componentClass; var props = _objectWithoutProperties(_props2, ['componentClass']); return _react2['default'].createElement( ComponentClass, _extends({}, props, { className: _classnames2['default'](props.className, 'form-control-static'), ref: 'input', key: 'input' }), this.getValue() ); }; return Static; })(_InputBase3['default']); Static.propTypes = { value: _utilsChildrenValueInputValidation2['default'], /** * You can override the default 'p' with a custom element */ componentClass: _reactPropTypesLibElementType2['default'], children: _utilsChildrenValueInputValidation2['default'] }; Static.defaultProps = { componentClass: 'p' }; exports['default'] = Static; module.exports = exports['default']; /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { // https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var REGEXP = /\%\((.+?)\)s/; var Interpolate = _react2['default'].createClass({ displayName: 'Interpolate', propTypes: { component: _react2['default'].PropTypes.node, format: _react2['default'].PropTypes.string, unsafe: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { component: 'span', unsafe: false }; }, render: function render() { var format = _utilsValidComponentChildren2['default'].hasValidComponent(this.props.children) || typeof this.props.children === 'string' ? this.props.children : this.props.format; var parent = this.props.component; var unsafe = this.props.unsafe === true; var props = _extends({}, this.props); delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { var content = format.split(REGEXP).reduce(function (memo, match, index) { var html = undefined; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (_react2['default'].isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return _react2['default'].createElement(parent, props); } var kids = format.split(REGEXP).reduce(function (memo, match, index) { var child = undefined; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return _react2['default'].createElement(parent, props, kids); } }); exports['default'] = Interpolate; module.exports = exports['default']; /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var Jumbotron = _react2['default'].createClass({ displayName: 'Jumbotron', propTypes: { /** * You can use a custom element for this component */ componentClass: _reactPropTypesLibElementType2['default'] }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, render: function render() { var ComponentClass = this.props.componentClass; return _react2['default'].createElement( ComponentClass, _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'jumbotron') }), this.props.children ); } }); exports['default'] = Jumbotron; module.exports = exports['default']; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); var Label = (function (_React$Component) { _inherits(Label, _React$Component); function Label() { _classCallCheck(this, _Label); _React$Component.apply(this, arguments); } Label.prototype.render = function render() { var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); return _react2['default'].createElement( 'span', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.children ); }; var _Label = Label; Label = _utilsBootstrapUtils.bsStyles(_styleMaps.State.values().concat(_styleMaps.DEFAULT, _styleMaps.PRIMARY), _styleMaps.DEFAULT)(Label) || Label; Label = _utilsBootstrapUtils.bsClass('label')(Label) || Label; return Label; })(_react2['default'].Component); exports['default'] = Label; module.exports = exports['default']; /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _ListGroupItem = __webpack_require__(179); var _ListGroupItem2 = _interopRequireDefault(_ListGroupItem); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); 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 _this = this; var items = _utilsValidComponentChildren2['default'].map(this.props.children, function (item, index) { return _react.cloneElement(item, { key: item.key ? item.key : index }); }); if (this.areCustomChildren(items)) { var Component = this.props.componentClass; return _react2['default'].createElement( Component, _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'list-group') }), items ); } var shouldRenderDiv = false; if (!this.props.children) { shouldRenderDiv = true; } else { _utilsValidComponentChildren2['default'].forEach(this.props.children, function (child) { if (_this.isAnchorOrButton(child.props)) { shouldRenderDiv = true; } }); } return shouldRenderDiv ? this.renderDiv(items) : this.renderUL(items); }; ListGroup.prototype.isAnchorOrButton = function isAnchorOrButton(props) { return props.href || props.onClick; }; ListGroup.prototype.areCustomChildren = function areCustomChildren(children) { var customChildren = false; _utilsValidComponentChildren2['default'].forEach(children, function (child) { if (child.type !== _ListGroupItem2['default']) { customChildren = true; } }, this); return customChildren; }; ListGroup.prototype.renderUL = function renderUL(items) { var listItems = _utilsValidComponentChildren2['default'].map(items, function (item) { return _react.cloneElement(item, { listItem: true }); }); return _react2['default'].createElement( 'ul', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'list-group') }), listItems ); }; ListGroup.prototype.renderDiv = function renderDiv(items) { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'list-group') }), items ); }; return ListGroup; })(_react2['default'].Component); ListGroup.defaultProps = { componentClass: 'div' }; ListGroup.propTypes = { className: _react2['default'].PropTypes.string, /** * The element for ListGroup if children are * user-defined custom components. * @type {("ul"|"div")} */ componentClass: _react2['default'].PropTypes.oneOf(['ul', 'div']), id: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]) }; exports['default'] = ListGroup; module.exports = exports['default']; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var ListGroupItem = (function (_React$Component) { _inherits(ListGroupItem, _React$Component); function ListGroupItem() { _classCallCheck(this, ListGroupItem); _React$Component.apply(this, arguments); } ListGroupItem.prototype.render = function render() { var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); classes.active = this.props.active; classes.disabled = this.props.disabled; if (this.props.href) { return this.renderAnchor(classes); } else if (this.props.onClick) { return this.renderButton(classes); } else if (this.props.listItem) { return this.renderLi(classes); } return this.renderSpan(classes); }; ListGroupItem.prototype.renderLi = function renderLi(classes) { return _react2['default'].createElement( 'li', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.header ? this.renderStructuredContent() : this.props.children ); }; ListGroupItem.prototype.renderAnchor = function renderAnchor(classes) { return _react2['default'].createElement( 'a', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.header ? this.renderStructuredContent() : this.props.children ); }; ListGroupItem.prototype.renderButton = function renderButton(classes) { return _react2['default'].createElement( 'button', _extends({ type: 'button' }, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.header ? this.renderStructuredContent() : this.props.children ); }; ListGroupItem.prototype.renderSpan = function renderSpan(classes) { return _react2['default'].createElement( 'span', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.header ? this.renderStructuredContent() : this.props.children ); }; ListGroupItem.prototype.renderStructuredContent = function renderStructuredContent() { var header = undefined; var headingClass = _utilsBootstrapUtils2['default'].prefix(this.props, 'heading'); if (_react2['default'].isValidElement(this.props.header)) { header = _react.cloneElement(this.props.header, { key: 'header', className: _classnames2['default'](this.props.header.props.className, headingClass) }); } else { header = _react2['default'].createElement( 'h4', { key: 'header', className: headingClass }, this.props.header ); } var content = _react2['default'].createElement( 'p', { key: 'content', className: _utilsBootstrapUtils2['default'].prefix(this.props, 'text') }, this.props.children ); return [header, content]; }; return ListGroupItem; })(_react2['default'].Component); ListGroupItem.propTypes = { className: _react2['default'].PropTypes.string, 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, eventKey: _react2['default'].PropTypes.any, href: _react2['default'].PropTypes.string, target: _react2['default'].PropTypes.string }; ListGroupItem.defaultTypes = { listItem: false }; exports['default'] = _utilsBootstrapUtils.bsStyles(_styleMaps.State.values(), _utilsBootstrapUtils.bsClass('list-group-item', ListGroupItem)); module.exports = exports['default']; /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _reactPropTypesLibAll = __webpack_require__(56); var _reactPropTypesLibAll2 = _interopRequireDefault(_reactPropTypesLibAll); var _SafeAnchor = __webpack_require__(43); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var MenuItem = (function (_React$Component) { _inherits(MenuItem, _React$Component); function MenuItem(props) { _classCallCheck(this, MenuItem); _React$Component.call(this, props); this.handleClick = this.handleClick.bind(this); } MenuItem.prototype.handleClick = function handleClick(event) { if (!this.props.href || this.props.disabled) { event.preventDefault(); } if (this.props.disabled) { return; } if (this.props.onSelect) { this.props.onSelect(this.props.eventKey, event); } }; MenuItem.prototype.render = function render() { var headerClass = _utilsBootstrapUtils2['default'].prefix(this.props, 'header'); if (this.props.divider) { return _react2['default'].createElement('li', { role: 'separator', className: _classnames2['default']('divider', this.props.className) }); } if (this.props.header) { return _react2['default'].createElement( 'li', { role: 'heading', className: headerClass }, this.props.children ); } var _props = this.props; var className = _props.className; var style = _props.style; var onClick = _props.onClick; var props = _objectWithoutProperties(_props, ['className', 'style', 'onClick']); var classes = { disabled: this.props.disabled, active: this.props.active }; return _react2['default'].createElement( 'li', { role: 'presentation', className: _classnames2['default'](className, classes), style: style }, _react2['default'].createElement(_SafeAnchor2['default'], _extends({}, props, { role: 'menuitem', tabIndex: '-1', onClick: _utilsCreateChainedFunction2['default'](onClick, this.handleClick) })) ); }; return MenuItem; })(_react2['default'].Component); MenuItem.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 (props) { if (props.divider && props.children) { return new Error('Children will not be rendered for dividers'); } }), /** * 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, /** * HTML `target` attribute corresponding to `a.target`. */ target: _react2['default'].PropTypes.string, /** * HTML `title` attribute corresponding to `a.title`. */ title: _react2['default'].PropTypes.string, /** * Callback fired when the menu item is clicked. */ onClick: _react2['default'].PropTypes.func, onKeyDown: _react2['default'].PropTypes.func, /** * Callback fired when the menu item is selected. * * ```js * function(Object event, Any eventKey) * ``` */ onSelect: _react2['default'].PropTypes.func, /** * HTML `id` attribute. */ id: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]) }; MenuItem.defaultProps = { divider: false, disabled: false, header: false }; exports['default'] = _utilsBootstrapUtils.bsClass('dropdown', MenuItem); module.exports = exports['default']; /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _Object$assign = __webpack_require__(10)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _MediaHeading = __webpack_require__(182); var _MediaHeading2 = _interopRequireDefault(_MediaHeading); var _MediaBody = __webpack_require__(183); var _MediaBody2 = _interopRequireDefault(_MediaBody); var _MediaLeft = __webpack_require__(184); var _MediaLeft2 = _interopRequireDefault(_MediaLeft); var _MediaRight = __webpack_require__(185); var _MediaRight2 = _interopRequireDefault(_MediaRight); var _MediaList = __webpack_require__(186); var _MediaList2 = _interopRequireDefault(_MediaList); var _MediaListItem = __webpack_require__(187); var _MediaListItem2 = _interopRequireDefault(_MediaListItem); var Media = _react2['default'].createClass({ displayName: 'Media', propTypes: { /** * You can use a custom element for the media container */ componentClass: _reactPropTypesLibElementType2['default'] }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, render: function render() { var _props = this.props; var ComponentClass = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); return _react2['default'].createElement(ComponentClass, _extends({}, props, { className: _classnames2['default'](className, 'media') })); } }); Media = _Object$assign(Media, { Heading: _MediaHeading2['default'], Body: _MediaBody2['default'], Left: _MediaLeft2['default'], Right: _MediaRight2['default'], List: _MediaList2['default'], ListItem: _MediaListItem2['default'] }); exports['default'] = Media; exports.Heading = _MediaHeading2['default']; exports.Body = _MediaBody2['default']; exports.Left = _MediaLeft2['default']; exports.Right = _MediaRight2['default']; exports.List = _MediaList2['default']; exports.ListItem = _MediaListItem2['default']; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var MediaHeading = _react2['default'].createClass({ displayName: 'Media.Heading', propTypes: { /** * You can use a custom element for the media heading */ componentClass: _reactPropTypesLibElementType2['default'] }, getDefaultProps: function getDefaultProps() { return { componentClass: 'h4' }; }, render: function render() { var _props = this.props; var ComponentClass = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); return _react2['default'].createElement(ComponentClass, _extends({}, props, { className: _classnames2['default'](className, 'media-heading') })); } }); exports['default'] = MediaHeading; module.exports = exports['default']; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var MediaBody = _react2['default'].createClass({ displayName: 'Media.Body', propTypes: { /** * You can use a custom element for the media body */ componentClass: _reactPropTypesLibElementType2['default'] }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, render: function render() { var _props = this.props; var ComponentClass = _props.componentClass; var className = _props.className; var props = _objectWithoutProperties(_props, ['componentClass', 'className']); return _react2['default'].createElement(ComponentClass, _extends({}, props, { className: _classnames2['default'](className, 'media-body') })); } }); exports['default'] = MediaBody; module.exports = exports['default']; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var MediaLeft = _react2['default'].createClass({ displayName: 'Media.Left', propTypes: { /** * Align the media to the top, middle or bottom * of the media object */ align: _react2['default'].PropTypes.oneOf(['top', 'middle', 'bottom']) }, render: function render() { var _classNames; var _props = this.props; var align = _props.align; var className = _props.className; var props = _objectWithoutProperties(_props, ['align', 'className']); var classes = _classnames2['default'](className, 'media-left', (_classNames = {}, _classNames['media-' + align] = Boolean(align), _classNames)); // Only add the media-alignment class if align is passed in props return _react2['default'].createElement('div', _extends({}, props, { className: classes })); } }); exports['default'] = MediaLeft; module.exports = exports['default']; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var MediaRight = _react2['default'].createClass({ displayName: 'Media.Right', propTypes: { /** * Align the media to the top, middle or bottom * of the media object */ align: _react2['default'].PropTypes.oneOf(['top', 'middle', 'bottom']) }, render: function render() { var _classNames; var _props = this.props; var align = _props.align; var className = _props.className; var props = _objectWithoutProperties(_props, ['align', 'className']); var classes = _classnames2['default'](className, 'media-right', (_classNames = {}, _classNames['media-' + align] = Boolean(align), _classNames)); // Only add the media-alignment class if align is passed in props return _react2['default'].createElement('div', _extends({}, props, { className: classes })); } }); exports['default'] = MediaRight; module.exports = exports['default']; /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var MediaList = _react2['default'].createClass({ displayName: 'Media.List', render: function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); return _react2['default'].createElement('ul', _extends({}, props, { className: _classnames2['default'](className, 'media-list') })); } }); exports['default'] = MediaList; module.exports = exports['default']; /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var MediaListItem = _react2['default'].createClass({ displayName: 'Media.ListItem', render: function render() { var _props = this.props; var className = _props.className; var props = _objectWithoutProperties(_props, ['className']); return _react2['default'].createElement('li', _extends({}, props, { className: _classnames2['default'](className, 'media') })); } }); exports['default'] = MediaListItem; module.exports = exports['default']; /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { /* eslint-disable react/prop-types */ 'use strict'; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _Object$keys = __webpack_require__(28)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); var _domHelpersUtilScrollbarSize = __webpack_require__(189); var _domHelpersUtilScrollbarSize2 = _interopRequireDefault(_domHelpersUtilScrollbarSize); var _domHelpersUtilInDOM = __webpack_require__(79); var _domHelpersUtilInDOM2 = _interopRequireDefault(_domHelpersUtilInDOM); var _domHelpersOwnerDocument = __webpack_require__(84); var _domHelpersOwnerDocument2 = _interopRequireDefault(_domHelpersOwnerDocument); var _domHelpersEvents = __webpack_require__(190); var _domHelpersEvents2 = _interopRequireDefault(_domHelpersEvents); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _Fade = __webpack_require__(193); var _Fade2 = _interopRequireDefault(_Fade); var _ModalDialog = __webpack_require__(194); var _ModalDialog2 = _interopRequireDefault(_ModalDialog); var _ModalBody = __webpack_require__(195); var _ModalBody2 = _interopRequireDefault(_ModalBody); var _ModalHeader = __webpack_require__(196); var _ModalHeader2 = _interopRequireDefault(_ModalHeader); var _ModalTitle = __webpack_require__(197); var _ModalTitle2 = _interopRequireDefault(_ModalTitle); var _ModalFooter = __webpack_require__(198); var _ModalFooter2 = _interopRequireDefault(_ModalFooter); var _reactOverlaysLibModal = __webpack_require__(199); var _reactOverlaysLibModal2 = _interopRequireDefault(_reactOverlaysLibModal); var _reactOverlaysLibUtilsIsOverflowing = __webpack_require__(210); var _reactOverlaysLibUtilsIsOverflowing2 = _interopRequireDefault(_reactOverlaysLibUtilsIsOverflowing); var _lodashCompatObjectPick = __webpack_require__(169); var _lodashCompatObjectPick2 = _interopRequireDefault(_lodashCompatObjectPick); var Modal = _react2['default'].createClass({ displayName: 'Modal', 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. */ dialogComponent: _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, /** * Hide this from automatic props documentation generation. * @private */ bsStyle: _react2['default'].PropTypes.string, /** * 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 }), childContextTypes: { '$bs_onModalHide': _react2['default'].PropTypes.func }, getDefaultProps: function getDefaultProps() { return _extends({}, _reactOverlaysLibModal2['default'].defaultProps, { bsClass: 'modal', animation: true, dialogComponent: _ModalDialog2['default'] }); }, getInitialState: function getInitialState() { return { modalStyles: {} }; }, getChildContext: function getChildContext() { return { $bs_onModalHide: this.props.onHide }; }, componentWillUnmount: function componentWillUnmount() { _domHelpersEvents2['default'].off(window, 'resize', this.handleWindowResize); }, render: function render() { var _this = this; var _props = this.props; var className = _props.className; var children = _props.children; var dialogClassName = _props.dialogClassName; var animation = _props.animation; var props = _objectWithoutProperties(_props, ['className', 'children', 'dialogClassName', 'animation']); var modalStyles = this.state.modalStyles; var inClass = { 'in': props.show && !animation }; var Dialog = props.dialogComponent; var parentProps = _lodashCompatObjectPick2['default'](props, _Object$keys(_reactOverlaysLibModal2['default'].propTypes).concat(['onExit', 'onExiting', 'onEnter', 'onEntered']) // the rest are fired in _onHide() and _onShow() ); var modal = _react2['default'].createElement( Dialog, _extends({ key: 'modal', ref: function (ref) { return _this._modal = ref; } }, props, { style: modalStyles, className: _classnames2['default'](className, inClass), dialogClassName: dialogClassName, onClick: props.backdrop === true ? this.handleDialogClick : null }), this.props.children ); return _react2['default'].createElement( _reactOverlaysLibModal2['default'], _extends({}, parentProps, { show: props.show, ref: function (ref) { _this._wrapper = ref && ref.refs.modal; _this._backdrop = ref && ref.refs.backdrop; }, onEntering: this._onShow, onExited: this._onHide, backdropClassName: _classnames2['default'](_utilsBootstrapUtils2['default'].prefix(props, 'backdrop'), inClass), containerClassName: _utilsBootstrapUtils2['default'].prefix(props, 'open'), transition: animation ? _Fade2['default'] : undefined, dialogTransitionTimeout: Modal.TRANSITION_DURATION, backdropTransitionTimeout: Modal.BACKDROP_TRANSITION_DURATION }), modal ); }, _onShow: function _onShow() { _domHelpersEvents2['default'].on(window, 'resize', this.handleWindowResize); this.setState(this._getStyles()); if (this.props.onEntering) { var _props2; (_props2 = this.props).onEntering.apply(_props2, arguments); } }, _onHide: function _onHide() { _domHelpersEvents2['default'].off(window, 'resize', this.handleWindowResize); if (this.props.onExited) { var _props3; (_props3 = this.props).onExited.apply(_props3, arguments); } }, handleDialogClick: function handleDialogClick(e) { if (e.target !== e.currentTarget) { return; } this.props.onHide(); }, handleWindowResize: function handleWindowResize() { this.setState(this._getStyles()); }, _getStyles: function _getStyles() { if (!_domHelpersUtilInDOM2['default']) { return {}; } var node = _reactDom2['default'].findDOMNode(this._modal); var doc = _domHelpersOwnerDocument2['default'](node); var scrollHt = node.scrollHeight; var bodyIsOverflowing = _reactOverlaysLibUtilsIsOverflowing2['default'](_reactDom2['default'].findDOMNode(this.props.container || doc.body)); var modalIsOverflowing = scrollHt > doc.documentElement.clientHeight; return { modalStyles: { paddingRight: bodyIsOverflowing && !modalIsOverflowing ? _domHelpersUtilScrollbarSize2['default']() : void 0, paddingLeft: !bodyIsOverflowing && modalIsOverflowing ? _domHelpersUtilScrollbarSize2['default']() : void 0 } }; } }); 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.bsSizes([_styleMaps.Sizes.LARGE, _styleMaps.Sizes.SMALL], _utilsBootstrapUtils.bsClass('modal', Modal)); module.exports = exports['default']; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(79); 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; }; /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var on = __webpack_require__(80), off = __webpack_require__(162), filter = __webpack_require__(191); module.exports = { on: on, off: off, filter: filter }; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var contains = __webpack_require__(85), qsa = __webpack_require__(192); 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); }; }; /***/ }, /* 192 */ /***/ 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)); }; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _reactOverlaysLibTransition = __webpack_require__(77); var _reactOverlaysLibTransition2 = _interopRequireDefault(_reactOverlaysLibTransition); var Fade = (function (_React$Component) { _inherits(Fade, _React$Component); function Fade() { _classCallCheck(this, Fade); _React$Component.apply(this, arguments); } // Explicitly copied from Transition for doc generation. // TODO: Remove duplication once #977 is resolved. Fade.prototype.render = function render() { var timeout = this.props.timeout; return _react2['default'].createElement( _reactOverlaysLibTransition2['default'], _extends({}, this.props, { timeout: timeout, className: _classnames2['default'](this.props.className, 'fade'), enteredClassName: 'in', enteringClassName: 'in' }), this.props.children ); }; return Fade; })(_react2['default'].Component); Fade.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 }; Fade.defaultProps = { 'in': false, timeout: 300, unmountOnExit: false, transitionAppear: false }; exports['default'] = Fade; module.exports = exports['default']; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { /* eslint-disable react/prop-types */ 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); var ModalDialog = _react2['default'].createClass({ displayName: 'ModalDialog', propTypes: { /** * A css class to apply to the Modal dialog DOM node. */ dialogClassName: _react2['default'].PropTypes.string }, render: function render() { var modalStyle = _extends({ display: 'block' }, this.props.style); var prefix = _utilsBootstrapUtils2['default'].prefix(this.props); var dialogClasses = _utilsBootstrapUtils2['default'].getClassSet(this.props); delete dialogClasses[prefix]; dialogClasses[_utilsBootstrapUtils2['default'].prefix(this.props, 'dialog')] = true; return _react2['default'].createElement( 'div', _extends({}, this.props, { title: null, tabIndex: '-1', role: 'dialog', style: modalStyle, className: _classnames2['default'](this.props.className, prefix) }), _react2['default'].createElement( 'div', { className: _classnames2['default'](this.props.dialogClassName, dialogClasses) }, _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'content'), role: 'document' }, this.props.children ) ) ); } }); exports['default'] = _utilsBootstrapUtils.bsSizes([_styleMaps.Sizes.LARGE, _styleMaps.Sizes.SMALL], _utilsBootstrapUtils.bsClass('modal', ModalDialog)); module.exports = exports['default']; /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var ModalBody = (function (_React$Component) { _inherits(ModalBody, _React$Component); function ModalBody() { _classCallCheck(this, ModalBody); _React$Component.apply(this, arguments); } ModalBody.prototype.render = function render() { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, _utilsBootstrapUtils2['default'].prefix(this.props, 'body')) }), this.props.children ); }; return ModalBody; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('modal', ModalBody); module.exports = exports['default']; /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); 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 props = _objectWithoutProperties(_props, ['aria-label']); var onHide = _utilsCreateChainedFunction2['default'](this.context.$bs_onModalHide, this.props.onHide); return _react2['default'].createElement( 'div', _extends({}, props, { className: _classnames2['default'](this.props.className, _utilsBootstrapUtils2['default'].prefix(this.props, 'header')) }), this.props.closeButton && _react2['default'].createElement( 'button', { type: 'button', className: 'close', 'aria-label': label, onClick: onHide }, _react2['default'].createElement( 'span', { 'aria-hidden': 'true' }, '×' ) ), this.props.children ); }; return ModalHeader; })(_react2['default'].Component); ModalHeader.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, bsClass: _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 }; ModalHeader.contextTypes = { '$bs_onModalHide': _react2['default'].PropTypes.func }; ModalHeader.defaultProps = { 'aria-label': 'Close', closeButton: false }; exports['default'] = _utilsBootstrapUtils.bsClass('modal', ModalHeader); module.exports = exports['default']; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var ModalTitle = (function (_React$Component) { _inherits(ModalTitle, _React$Component); function ModalTitle() { _classCallCheck(this, ModalTitle); _React$Component.apply(this, arguments); } ModalTitle.prototype.render = function render() { return _react2['default'].createElement( 'h4', _extends({}, this.props, { className: _classnames2['default'](this.props.className, _utilsBootstrapUtils2['default'].prefix(this.props, 'title')) }), this.props.children ); }; return ModalTitle; })(_react2['default'].Component); exports['default'] = _utilsBootstrapUtils.bsClass('modal', ModalTitle); module.exports = exports['default']; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var ModalFooter = (function (_React$Component) { _inherits(ModalFooter, _React$Component); function ModalFooter() { _classCallCheck(this, ModalFooter); _React$Component.apply(this, arguments); } ModalFooter.prototype.render = function render() { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, _utilsBootstrapUtils2['default'].prefix(this.props, 'footer')) }), this.props.children ); }; return ModalFooter; })(_react2['default'].Component); ModalFooter.propTypes = { /** * A css class applied to the Component */ bsClass: _react2['default'].PropTypes.string }; ModalFooter.defaultProps = { bsClass: 'modal' }; exports['default'] = _utilsBootstrapUtils.bsClass('modal', ModalFooter); module.exports = exports['default']; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { /*eslint-disable react/prop-types */ '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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(33); var _warning2 = _interopRequireDefault(_warning); var _reactPropTypesLibMountable = __webpack_require__(200); var _reactPropTypesLibMountable2 = _interopRequireDefault(_reactPropTypesLibMountable); var _reactPropTypesLibElementType = __webpack_require__(202); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _Portal = __webpack_require__(203); var _Portal2 = _interopRequireDefault(_Portal); var _ModalManager = __webpack_require__(205); var _ModalManager2 = _interopRequireDefault(_ModalManager); var _utilsOwnerDocument = __webpack_require__(164); var _utilsOwnerDocument2 = _interopRequireDefault(_utilsOwnerDocument); var _utilsAddEventListener = __webpack_require__(161); var _utilsAddEventListener2 = _interopRequireDefault(_utilsAddEventListener); var _utilsAddFocusListener = __webpack_require__(213); var _utilsAddFocusListener2 = _interopRequireDefault(_utilsAddFocusListener); var _domHelpersUtilInDOM = __webpack_require__(79); var _domHelpersUtilInDOM2 = _interopRequireDefault(_domHelpersUtilInDOM); var _domHelpersActiveElement = __webpack_require__(83); var _domHelpersActiveElement2 = _interopRequireDefault(_domHelpersActiveElement); var _domHelpersQueryContains = __webpack_require__(85); var _domHelpersQueryContains2 = _interopRequireDefault(_domHelpersQueryContains); var _utilsGetContainer = __webpack_require__(204); var _utilsGetContainer2 = _interopRequireDefault(_utilsGetContainer); 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. * */ var Modal = _react2['default'].createClass({ displayName: 'Modal', propTypes: _extends({}, _Portal2['default'].propTypes, { /** * 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([_reactPropTypesLibMountable2['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: _reactPropTypesLibElementType2['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. * 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 }), 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 children = _props.children; var Transition = _props.transition; var backdrop = _props.backdrop; var dialogTransitionTimeout = _props.dialogTransitionTimeout; var props = _objectWithoutProperties(_props, ['children', 'transition', 'backdrop', 'dialogTransitionTimeout']); var onExit = props.onExit; var onExiting = props.onExiting; var onEnter = props.onEnter; var onEntering = props.onEntering; var onEntered = props.onEntered; var show = !!props.show; var dialog = _react2['default'].Children.only(this.props.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 = _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: props.container }, _react2['default'].createElement( 'div', { ref: 'modal', role: props.role || 'dialog', style: props.style, className: props.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 (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 = _utilsOwnerDocument2['default'](this); var container = _utilsGetContainer2['default'](this.props.container, doc.body); modalManager.add(this, container, this.props.containerClassName); this._onDocumentKeyupListener = _utilsAddEventListener2['default'](doc, 'keyup', this.handleDocumentKeyUp); this._onFocusinListener = _utilsAddFocusListener2['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 (_domHelpersUtilInDOM2['default']) { this.lastFocus = _domHelpersActiveElement2['default'](); } }, focus: function focus() { var autoFocus = this.props.autoFocus; var modalContent = this.getDialogElement(); var current = _domHelpersActiveElement2['default'](_utilsOwnerDocument2['default'](this)); var focusInModal = current && _domHelpersQueryContains2['default'](modalContent, current); if (modalContent && autoFocus && !focusInModal) { this.lastFocus = current; if (!modalContent.hasAttribute('tabIndex')) { modalContent.setAttribute('tabIndex', -1); _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 = _domHelpersActiveElement2['default'](_utilsOwnerDocument2['default'](this)); var modal = this.getDialogElement(); if (modal && modal !== active && !_domHelpersQueryContains2['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']; /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _common = __webpack_require__(201); /** * 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']; /***/ }, /* 201 */ /***/ 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; } /***/ }, /* 202 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _common = __webpack_require__(201); /** * 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']; /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactPropTypesLibMountable = __webpack_require__(200); var _reactPropTypesLibMountable2 = _interopRequireDefault(_reactPropTypesLibMountable); var _utilsOwnerDocument = __webpack_require__(164); var _utilsOwnerDocument2 = _interopRequireDefault(_utilsOwnerDocument); var _utilsGetContainer = __webpack_require__(204); var _utilsGetContainer2 = _interopRequireDefault(_utilsGetContainer); /** * 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([_reactPropTypesLibMountable2['default'], _react2['default'].PropTypes.func]) }, componentDidMount: function componentDidMount() { this._renderOverlay(); }, componentDidUpdate: function componentDidUpdate() { this._renderOverlay(); }, componentWillUnmount: function componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget: function _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); this.getContainerDOMNode().appendChild(this._overlayTarget); } }, _unmountOverlayTarget: function _unmountOverlayTarget() { if (this._overlayTarget) { this.getContainerDOMNode().removeChild(this._overlayTarget); this._overlayTarget = 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; }, getContainerDOMNode: function getContainerDOMNode() { return _utilsGetContainer2['default'](this.props.container, _utilsOwnerDocument2['default'](this).body); } }); exports['default'] = Portal; module.exports = exports['default']; /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = getContainer; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); function getContainer(container, defaultContainer) { container = typeof container === 'function' ? container() : container; return _reactDom2['default'].findDOMNode(container) || defaultContainer; } module.exports = exports['default']; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _domHelpersStyle = __webpack_require__(69); var _domHelpersStyle2 = _interopRequireDefault(_domHelpersStyle); var _domHelpersClass = __webpack_require__(206); var _domHelpersClass2 = _interopRequireDefault(_domHelpersClass); var _domHelpersUtilScrollbarSize = __webpack_require__(189); var _domHelpersUtilScrollbarSize2 = _interopRequireDefault(_domHelpersUtilScrollbarSize); var _utilsIsOverflowing = __webpack_require__(210); var _utilsIsOverflowing2 = _interopRequireDefault(_utilsIsOverflowing); var _utilsManageAriaHidden = __webpack_require__(212); 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 = []; } ModalManager.prototype.add = 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) { _utilsManageAriaHidden.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 = _utilsIsOverflowing2['default'](container); if (data.overflowing) { // use computed style, here to get the real padding // to add our scrollbar width style.paddingRight = parseInt(_domHelpersStyle2['default'](container, 'paddingRight') || 0, 10) + _domHelpersUtilScrollbarSize2['default']() + 'px'; } _domHelpersStyle2['default'](container, style); data.classes.forEach(_domHelpersClass2['default'].addClass.bind(null, container)); this.containers.push(container); this.data.push(data); return modalIdx; }; ModalManager.prototype.remove = 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(_domHelpersClass2['default'].removeClass.bind(null, container)); if (this.hideSiblingNodes) { _utilsManageAriaHidden.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 _utilsManageAriaHidden.ariaHidden(false, data.modals[data.modals.length - 1].mountNode); } }; ModalManager.prototype.isTopModal = function isTopModal(modal) { return !!this.modals.length && this.modals[this.modals.length - 1] === modal; }; return ModalManager; })(); exports['default'] = ModalManager; module.exports = exports['default']; /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = { addClass: __webpack_require__(207), removeClass: __webpack_require__(209), hasClass: __webpack_require__(208) }; /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var hasClass = __webpack_require__(208); module.exports = function addClass(element, className) { if (element.classList) element.classList.add(className);else if (!hasClass(element)) element.className = element.className + ' ' + className; }; /***/ }, /* 208 */ /***/ 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; }; /***/ }, /* 209 */ /***/ 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, ''); }; /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = isOverflowing; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _domHelpersQueryIsWindow = __webpack_require__(211); var _domHelpersQueryIsWindow2 = _interopRequireDefault(_domHelpersQueryIsWindow); var _domHelpersOwnerDocument = __webpack_require__(84); var _domHelpersOwnerDocument2 = _interopRequireDefault(_domHelpersOwnerDocument); function isBody(node) { return node && node.tagName.toLowerCase() === 'body'; } function bodyIsOverflowing(node) { var doc = _domHelpersOwnerDocument2['default'](node); var win = _domHelpersQueryIsWindow2['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 = _domHelpersQueryIsWindow2['default'](container); return win || isBody(container) ? bodyIsOverflowing(container) : container.scrollHeight > container.clientHeight; } module.exports = exports['default']; /***/ }, /* 211 */ /***/ function(module, exports) { 'use strict'; module.exports = function getWindow(node) { return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false; }; /***/ }, /* 212 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = 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); }); } /***/ }, /* 213 */ /***/ function(module, exports) { /** * 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 */ 'use strict'; exports.__esModule = true; exports['default'] = addFocusListener; function addFocusListener(handler) { var useFocusin = !document.addEventListener; var remove = undefined; if (useFocusin) { document.attachEvent('onfocusin', handler); remove = function () { return document.detachEvent('onfocusin', handler); }; } else { document.addEventListener('focus', handler, true); remove = function () { return document.removeEventListener('focus', handler, true); }; } return { remove: remove }; } module.exports = exports['default']; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _reactPropTypesLibAll = __webpack_require__(56); var _reactPropTypesLibAll2 = _interopRequireDefault(_reactPropTypesLibAll); var _warning = __webpack_require__(33); var _warning2 = _interopRequireDefault(_warning); var _keycode = __webpack_require__(86); var _keycode2 = _interopRequireDefault(_keycode); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _utilsTabUtils = __webpack_require__(215); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var Nav = (function (_React$Component) { _inherits(Nav, _React$Component); function Nav() { _classCallCheck(this, Nav); _React$Component.apply(this, arguments); } Nav.prototype.componentDidUpdate = function componentDidUpdate() { if (this._needsRefocus) { var ul = this.refs.ul && _reactDom2['default'].findDOMNode(this.refs.ul); var tabs = ul ? ul.children || [] : []; var tabIdx = this.eventKeys().indexOf(this.getActiveKey()); this._needsRefocus = false; if (tabIdx !== -1) { var tabNode = tabs[tabIdx]; if (tabNode && tabNode.firstChild) { tabNode.firstChild.focus(); } } } }; Nav.prototype.render = function render() { var className = this.props.className; var isNavbar = this.props.navbar != null ? this.props.navbar : this.context.$bs_navbar; var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'stacked')] = this.props.stacked; classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'justified')] = this.props.justified; if (isNavbar) { var bsClass = this.context.$bs_navbar_bsClass || 'navbar'; var navbarRight = this.props.pullRight; classes[_utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'nav')] = true; classes[_utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'right')] = navbarRight; classes[_utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'left')] = this.props.pullLeft; } else { classes['pull-right'] = this.props.pullRight; classes['pull-left'] = this.props.pullLeft; } var list = _react2['default'].createElement( 'ul', _extends({ ref: 'ul' }, this.props, { role: this.getNavRole(), className: _classnames2['default'](className, classes) }), _utilsValidComponentChildren2['default'].map(this.props.children, this.renderNavItem, this) ); return list; }; Nav.prototype.renderNavItem = function renderNavItem(child, index) { var onSelect = _utilsCreateChainedFunction2['default'](child.props.onSelect, this.props.onSelect); var active = this.isChildActive(child); var tabProps = this.getTabProps(child, index, active, onSelect); return _react.cloneElement(child, _extends({ active: active, onSelect: onSelect, key: child.key || index, navItem: true }, tabProps)); }; Nav.prototype.getActiveKey = function getActiveKey() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var context = arguments.length <= 1 || arguments[1] === undefined ? this.context : arguments[1]; var activeKey = props.activeKey; context = this.getContext('$bs_tabcontainer', context); if (context.activeKey) { true ? _warning2['default'](activeKey == null || props.activeHref, 'Specifing a Nav `activeKey` or `activeHref` prop in the context of a `TabContainer` is not supported. ' + 'Instead use `<TabContainer activeKey={' + activeKey + '} />`') : undefined; activeKey = context.activeKey; } return activeKey; }; Nav.prototype.isChildActive = function isChildActive(child) { var activeKey = this.getActiveKey(); if (this.context.$bs_tabcontainer) { true ? _warning2['default'](!child.props.active, 'Specifing a NavItem `active` prop in the context of a `TabContainer` is not supported. Instead ' + 'use `<TabContainer activeKey={' + child.props.eventKey + '} />`') : undefined; return child.props.eventKey === activeKey; } if (child.props.active) { return true; } if (this.props.activeKey != null) { if (child.props.eventKey === this.props.activeKey) { return true; } } if (this.props.activeHref != null) { if (child.props.href === this.props.activeHref) { return true; } } return child.props.active; }; Nav.prototype.getTabProps = function getTabProps(child, idx, isActive, onSelect) { var _child$props = child.props; var linkId = _child$props.linkId; var controls = _child$props['aria-controls']; var eventKey = _child$props.eventKey; var role = _child$props.role; var onKeyDown = _child$props.onKeyDown; var _child$props$tabIndex = _child$props.tabIndex; var tabIndex = _child$props$tabIndex === undefined ? 0 : _child$props$tabIndex; var navRole = this.getNavRole(); var context = this.getContext('$bs_tabcontainer'); if (context.getId) { true ? _warning2['default'](!(linkId || controls), 'In the context of a TabContainer, NavItems are given generated `linkId` 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; linkId = context.getId(eventKey, _utilsTabUtils.TAB) || null; controls = context.getId(eventKey, _utilsTabUtils.PANE) || null; onSelect = _utilsCreateChainedFunction2['default'](onSelect, context.onSelect); } if (navRole === 'tablist') { role = role || 'tab'; onKeyDown = _utilsCreateChainedFunction2['default'](this.handleTabKeyDown.bind(this, onSelect || function () {}), onKeyDown); } return { onSelect: onSelect, linkId: linkId, role: role, onKeyDown: onKeyDown, 'aria-controls': controls, tabIndex: isActive ? tabIndex : -1 }; }; Nav.prototype.handleTabKeyDown = function handleTabKeyDown(onSelect, event) { var keys = this.eventKeys(); var currentKey = this.getActiveKey() || keys[0]; var next = undefined; switch (event.keyCode) { case _keycode2['default'].codes.left: case _keycode2['default'].codes.up: next = _utilsTabUtils.nextEnabled(this.props.children, currentKey, keys, false); if (next && next !== currentKey) { event.preventDefault(); onSelect(next); this._needsRefocus = true; } break; case _keycode2['default'].codes.right: case _keycode2['default'].codes.down: next = _utilsTabUtils.nextEnabled(this.props.children, currentKey, keys, true); if (next && next !== currentKey) { event.preventDefault(); onSelect(next); this._needsRefocus = true; } break; default: } }; Nav.prototype.eventKeys = function eventKeys() { var keys = []; _utilsValidComponentChildren2['default'].forEach(this.props.children, function (_ref) { var eventKey = _ref.props.eventKey; return keys.push(eventKey); }); return keys; }; Nav.prototype.getNavRole = function getNavRole() { return this.props.role || (this.context.$bs_tabcontainer ? 'tablist' : null); }; Nav.prototype.getContext = function getContext(key) { return this.context[key] || {}; }; return Nav; })(_react2['default'].Component); Nav.propTypes = { /** * Marks the child NavItem with a matching `href` prop as active. */ activeHref: _react2['default'].PropTypes.string, /** * Marks the NavItem with a matching `eventKey` as active. Has a * higher precedence over `activeHref`. */ activeKey: _react2['default'].PropTypes.any, /** * NavItems are be positioned vertically. */ stacked: _react2['default'].PropTypes.bool, justified: _reactPropTypesLibAll2['default'](_react2['default'].PropTypes.bool, function (_ref2) { var justified = _ref2.justified; var navbar = _ref2.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, /** * CSS classes for the wrapper `nav` element */ className: _react2['default'].PropTypes.string, /** * HTML id for the wrapper `nav` element */ id: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]), /** * 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 }; Nav.contextTypes = { $bs_navbar: _react2['default'].PropTypes.bool, $bs_navbar_bsClass: _react2['default'].PropTypes.string, $bs_deprecated_navbar: _react2['default'].PropTypes.bool, $bs_tabcontainer: _react2['default'].PropTypes.shape({ activeKey: _react2['default'].PropTypes.any, onSelect: _react2['default'].PropTypes.func, getId: _react2['default'].PropTypes.func }) }; Nav.defaultProps = { justified: false, pullRight: false, pullLeft: false, stacked: false }; exports['default'] = _utilsBootstrapUtils.bsClass('nav', _utilsBootstrapUtils.bsStyles(['tabs', 'pills'], Nav)); module.exports = exports['default']; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; exports.nextEnabled = nextEnabled; var _ValidComponentChildren = __webpack_require__(7); var _ValidComponentChildren2 = _interopRequireDefault(_ValidComponentChildren); var findChild = _ValidComponentChildren2['default'].find; var TAB = 'tab'; exports.TAB = TAB; var PANE = 'pane'; exports.PANE = PANE; function nextEnabled(children, currentKey, keys, moveNext) { var lastIdx = keys.length - 1; var stopAt = keys[moveNext ? Math.max(lastIdx, 0) : 0]; var nextKey = currentKey; function getNext() { var idx = keys.indexOf(nextKey); nextKey = moveNext ? keys[Math.min(lastIdx, idx + 1)] : keys[Math.max(0, idx - 1)]; return findChild(children, function (_child) { return _child.props.eventKey === nextKey; }); } var next = getNext(); while (next.props.eventKey !== stopAt && next.props.disabled) { next = getNext(); } return next.props.disabled ? currentKey : next.props.eventKey; } /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { /* eslint react/no-multi-comp: 0 */ 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _uncontrollable = __webpack_require__(156); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _Grid = __webpack_require__(170); var _Grid2 = _interopRequireDefault(_Grid); var _NavbarBrand = __webpack_require__(217); var _NavbarBrand2 = _interopRequireDefault(_NavbarBrand); var _NavbarHeader = __webpack_require__(218); var _NavbarHeader2 = _interopRequireDefault(_NavbarHeader); var _NavbarToggle = __webpack_require__(219); var _NavbarToggle2 = _interopRequireDefault(_NavbarToggle); var _NavbarCollapse = __webpack_require__(220); var _NavbarCollapse2 = _interopRequireDefault(_NavbarCollapse); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); var Navbar = _react2['default'].createClass({ displayName: 'Navbar', 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 }, childContextTypes: { $bs_navbar: _react.PropTypes.bool, $bs_navbar_bsClass: _react.PropTypes.string, $bs_navbar_onToggle: _react.PropTypes.func, $bs_navbar_expanded: _react.PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { componentClass: 'nav', fixedTop: false, fixedBottom: false, staticTop: false, inverse: false, fluid: false }; }, getChildContext: function getChildContext() { return { $bs_navbar: true, $bs_navbar_bsClass: this.props.bsClass, $bs_navbar_onToggle: this.handleToggle, $bs_navbar_expanded: this.props.expanded }; }, handleToggle: function handleToggle() { this.props.onToggle(!this.props.expanded); }, isNavExpanded: function isNavExpanded() { return !!this.props.expanded; }, render: function render() { var _props = this.props; var fixedTop = _props.fixedTop; var fixedBottom = _props.fixedBottom; var staticTop = _props.staticTop; var inverse = _props.inverse; var ComponentClass = _props.componentClass; var fluid = _props.fluid; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['fixedTop', 'fixedBottom', 'staticTop', 'inverse', 'componentClass', 'fluid', 'className', 'children']); // 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 (props.role === undefined && ComponentClass !== 'nav') { props.role = 'navigation'; } if (inverse) { props.bsStyle = _styleMaps.INVERSE; } var classes = _utilsBootstrapUtils2['default'].getClassSet(props); classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'fixed-top')] = fixedTop; classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'fixed-bottom')] = fixedBottom; classes[_utilsBootstrapUtils2['default'].prefix(this.props, 'static-top')] = staticTop; return _react2['default'].createElement( ComponentClass, _extends({}, props, { className: _classnames2['default'](className, classes) }), _react2['default'].createElement( _Grid2['default'], { fluid: fluid }, children ) ); } }); var NAVBAR_STATES = [_styleMaps.DEFAULT, _styleMaps.INVERSE]; Navbar = _utilsBootstrapUtils.bsStyles(NAVBAR_STATES, _styleMaps.DEFAULT, _utilsBootstrapUtils.bsClass('navbar', _uncontrollable2['default'](Navbar, { expanded: 'onToggle' }))); function createSimpleWrapper(tag, suffix, displayName) { var wrapper = function wrapper(_ref, _ref2) { var Tag = _ref.componentClass; var className = _ref.className; var props = _objectWithoutProperties(_ref, ['componentClass', 'className']); var _classNames; var _ref2$$bs_navbar_bsClass = _ref2.$bs_navbar_bsClass; var bsClass = _ref2$$bs_navbar_bsClass === undefined ? 'navbar' : _ref2$$bs_navbar_bsClass; return _react2['default'].createElement(Tag, _extends({}, props, { className: _classnames2['default'](className, _utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, suffix), (_classNames = {}, _classNames[_utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'right')] = props.pullRight, _classNames[_utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'left')] = props.pullLeft, _classNames)) })); }; 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_bsClass: _react.PropTypes.string }; return wrapper; } Navbar.Brand = _NavbarBrand2['default']; Navbar.Header = _NavbarHeader2['default']; Navbar.Toggle = _NavbarToggle2['default']; Navbar.Collapse = _NavbarCollapse2['default']; Navbar.Form = createSimpleWrapper('div', 'form', 'NavbarForm'); Navbar.Text = createSimpleWrapper('p', 'text', 'NavbarText'); Navbar.Link = createSimpleWrapper('a', 'link', 'NavbarLink'); exports['default'] = Navbar; module.exports = exports['default']; /***/ }, /* 217 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); 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 _context$$bs_navbar_bsClass = this.context.$bs_navbar_bsClass; var bsClass = _context$$bs_navbar_bsClass === undefined ? 'navbar' : _context$$bs_navbar_bsClass; var brandClasses = _utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'brand'); if (_react2['default'].isValidElement(children)) { return _react2['default'].cloneElement(children, { className: _classnames2['default'](children.props.className, className, brandClasses) }); } return _react2['default'].createElement( 'span', _extends({}, props, { className: _classnames2['default'](className, brandClasses) }), children ); }; return NavbarBrand; })(_react2['default'].Component); NavbarBrand.contextTypes = { $bs_navbar_bsClass: _react2['default'].PropTypes.string }; exports['default'] = NavbarBrand; module.exports = exports['default']; /***/ }, /* 218 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var NavbarHeader = _react2['default'].createClass({ displayName: 'NavbarHeader', contextTypes: { $bs_navbar_bsClass: _react.PropTypes.string }, render: function render() { var _props = this.props; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['className', 'children']); var _context$$bs_navbar_bsClass = this.context.$bs_navbar_bsClass; var bsClass = _context$$bs_navbar_bsClass === undefined ? 'navbar' : _context$$bs_navbar_bsClass; var headerClasses = _utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'header'); return _react2['default'].createElement( 'div', { className: _classnames2['default'](className, headerClasses) }, children ); } }); exports['default'] = NavbarHeader; module.exports = exports['default']; /***/ }, /* 219 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var NavbarToggle = _react2['default'].createClass({ displayName: 'NavbarToggle', propTypes: { /** * The toggle content, if left empty it will render the default toggle (seen above). */ children: _react.PropTypes.node }, contextTypes: { $bs_navbar_bsClass: _react.PropTypes.string, $bs_navbar_onToggle: _react.PropTypes.func }, render: function render() { var _props = this.props; var children = _props.children; var props = _objectWithoutProperties(_props, ['children']); var _context = this.context; var _context$$bs_navbar_bsClass = _context.$bs_navbar_bsClass; var bsClass = _context$$bs_navbar_bsClass === undefined ? 'navbar' : _context$$bs_navbar_bsClass; var onToggle = _context.$bs_navbar_onToggle; return _react2['default'].createElement( 'button', { type: 'button', onClick: onToggle, className: _utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'toggle') }, children || [_react2['default'].createElement( 'span', { className: 'sr-only', key: 0 }, 'Toggle navigation' ), _react2['default'].createElement('span', { className: 'icon-bar', key: 1 }), _react2['default'].createElement('span', { className: 'icon-bar', key: 2 }), _react2['default'].createElement('span', { className: 'icon-bar', key: 3 })] ); } }); exports['default'] = NavbarToggle; module.exports = exports['default']; /***/ }, /* 220 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _Collapse = __webpack_require__(68); var _Collapse2 = _interopRequireDefault(_Collapse); var NavbarCollapse = _react2['default'].createClass({ displayName: 'NavbarCollapse', contextTypes: { $bs_navbar_bsClass: _react.PropTypes.string, $bs_navbar_expanded: _react.PropTypes.bool }, render: function render() { var _props = this.props; var children = _props.children; var props = _objectWithoutProperties(_props, ['children']); var _context = this.context; var _context$$bs_navbar_bsClass = _context.$bs_navbar_bsClass; var bsClass = _context$$bs_navbar_bsClass === undefined ? 'navbar' : _context$$bs_navbar_bsClass; var expanded = _context.$bs_navbar_expanded; return _react2['default'].createElement( _Collapse2['default'], _extends({ 'in': expanded }, props), _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'collapse') }, children ) ); } }); exports['default'] = NavbarCollapse; module.exports = exports['default']; /***/ }, /* 221 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Dropdown = __webpack_require__(82); var _Dropdown2 = _interopRequireDefault(_Dropdown); 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 children = _props.children; var title = _props.title; var noCaret = _props.noCaret; var props = _objectWithoutProperties(_props, ['children', 'title', 'noCaret']); return _react2['default'].createElement( _Dropdown2['default'], _extends({}, props, { componentClass: 'li' }), _react2['default'].createElement( _Dropdown2['default'].Toggle, { useAnchor: true, disabled: props.disabled, noCaret: noCaret }, title ), _react2['default'].createElement( _Dropdown2['default'].Menu, null, children ) ); }; return NavDropdown; })(_react2['default'].Component); NavDropdown.propTypes = _extends({ noCaret: _react2['default'].PropTypes.bool, title: _react2['default'].PropTypes.node.isRequired }, _Dropdown2['default'].propTypes); exports['default'] = NavDropdown; module.exports = exports['default']; /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _SafeAnchor = __webpack_require__(43); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var NavItem = _react2['default'].createClass({ displayName: 'NavItem', propTypes: { linkId: _react2['default'].PropTypes.string, onSelect: _react2['default'].PropTypes.func, active: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, href: _react2['default'].PropTypes.string, onClick: _react2['default'].PropTypes.func, role: _react2['default'].PropTypes.string, title: _react2['default'].PropTypes.node, eventKey: _react2['default'].PropTypes.any, target: _react2['default'].PropTypes.string, 'aria-controls': _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { active: false, disabled: false }; }, render: function render() { var _props = this.props; var role = _props.role; var linkId = _props.linkId; var disabled = _props.disabled; var active = _props.active; var href = _props.href; var onClick = _props.onClick; var title = _props.title; var target = _props.target; var children = _props.children; var tabIndex = _props.tabIndex; var ariaControls = _props['aria-controls']; var props = _objectWithoutProperties(_props, ['role', 'linkId', 'disabled', 'active', 'href', 'onClick', 'title', 'target', 'children', 'tabIndex', 'aria-controls']); var classes = { active: active, disabled: disabled }; var linkProps = { role: role, href: href, onClick: _utilsCreateChainedFunction2['default'](onClick, this.handleClick), title: title, target: target, tabIndex: tabIndex, id: linkId }; if (!role && href === '#') { linkProps.role = 'button'; } else if (role === 'tab') { linkProps['aria-selected'] = active; } return _react2['default'].createElement( 'li', _extends({}, props, { role: 'presentation', className: _classnames2['default'](props.className, classes) }), _react2['default'].createElement( _SafeAnchor2['default'], _extends({}, linkProps, { 'aria-controls': ariaControls }), children ) ); }, handleClick: function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, e); } } } }); exports['default'] = NavItem; module.exports = exports['default']; //eslint-disable-line /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { /* eslint react/prop-types: [2, {ignore: ["container", "containerPadding", "target", "placement", "children"] }] */ /* These properties are validated in 'Portal' and 'Position' components */ 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactOverlaysLibOverlay = __webpack_require__(224); var _reactOverlaysLibOverlay2 = _interopRequireDefault(_reactOverlaysLibOverlay); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _Fade = __webpack_require__(193); var _Fade2 = _interopRequireDefault(_Fade); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); 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 child = _props.children; var transition = _props.animation; var props = _objectWithoutProperties(_props, ['children', 'animation']); if (transition === true) { transition = _Fade2['default']; } if (transition === false) { transition = null; } if (!transition) { child = _react.cloneElement(child, { className: _classnames2['default']('in', child.props.className) }); } return _react2['default'].createElement( _reactOverlaysLibOverlay2['default'], _extends({}, props, { transition: transition }), child ); }; return Overlay; })(_react2['default'].Component); Overlay.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 }); Overlay.defaultProps = { animation: _Fade2['default'], rootClose: false, show: false }; exports['default'] = Overlay; module.exports = exports['default']; /***/ }, /* 224 */ /***/ 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; }; 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 _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Portal = __webpack_require__(203); var _Portal2 = _interopRequireDefault(_Portal); var _Position = __webpack_require__(225); var _Position2 = _interopRequireDefault(_Position); var _RootCloseWrapper = __webpack_require__(160); var _RootCloseWrapper2 = _interopRequireDefault(_RootCloseWrapper); var _reactPropTypesLibElementType = __webpack_require__(202); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); /** * 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); _React$Component.call(this, props, context); this.state = { exited: !props.show }; this.onHiddenListener = this.handleHidden.bind(this); } Overlay.prototype.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 }); } }; Overlay.prototype.render = 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 ); }; Overlay.prototype.handleHidden = 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. */ onHide: _react2['default'].PropTypes.func, /** * A `<Transition/>` component used to animate the overlay changes visibility. */ transition: _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 }); exports['default'] = Overlay; module.exports = exports['default']; /***/ }, /* 225 */ /***/ 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; }; 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 _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsOwnerDocument = __webpack_require__(164); var _utilsOwnerDocument2 = _interopRequireDefault(_utilsOwnerDocument); var _utilsGetContainer = __webpack_require__(204); var _utilsGetContainer2 = _interopRequireDefault(_utilsGetContainer); var _utilsOverlayPositionUtils = __webpack_require__(226); var _reactPropTypesLibMountable = __webpack_require__(200); var _reactPropTypesLibMountable2 = _interopRequireDefault(_reactPropTypesLibMountable); /** * The Position component calulates the corrdinates 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); _React$Component.call(this, props, context); this.state = { positionLeft: 0, positionTop: 0, arrowOffsetLeft: null, arrowOffsetTop: null }; this._needsFlush = false; this._lastTarget = null; } Position.prototype.componentDidMount = function componentDidMount() { this.updatePosition(); }; Position.prototype.componentWillReceiveProps = function componentWillReceiveProps() { this._needsFlush = true; }; Position.prototype.componentDidUpdate = function componentDidUpdate(prevProps) { if (this._needsFlush) { this._needsFlush = false; this.updatePosition(prevProps.placement !== this.props.placement); } }; Position.prototype.componentWillUnmount = function componentWillUnmount() { // Probably not necessary, but just in case holding a reference to the // target causes problems somewhere. this._lastTarget = null; }; Position.prototype.render = 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; var child = _react2['default'].Children.only(children); return _react.cloneElement(child, _extends({}, props, arrowPosition, { //do we need to also forward positionLeft and positionTop if they are set to style? positionLeft: positionLeft, positionTop: positionTop, className: _classnames2['default'](className, child.props.className), style: _extends({}, child.props.style, { left: positionLeft, top: positionTop }) })); }; Position.prototype.getTargetSafe = function getTargetSafe() { if (!this.props.target) { return null; } var target = this.props.target(this.props); if (!target) { // This is so we can just use === check below on all falsy targets. return null; } return target; }; Position.prototype.updatePosition = function updatePosition(placementChanged) { var target = this.getTargetSafe(); if (!this.props.shouldUpdatePosition && target === this._lastTarget && !placementChanged) { return; } this._lastTarget = target; if (!target) { this.setState({ positionLeft: 0, positionTop: 0, arrowOffsetLeft: null, arrowOffsetTop: null }); return; } var overlay = _reactDom2['default'].findDOMNode(this); var container = _utilsGetContainer2['default'](this.props.container, _utilsOwnerDocument2['default'](this).body); this.setState(_utilsOverlayPositionUtils.calcOverlayPosition(this.props.placement, overlay, target, container, this.props.containerPadding)); }; return Position; })(_react2['default'].Component); Position.propTypes = { /** * Function mapping props to a DOM node the component is positioned next to * */ target: _react2['default'].PropTypes.func, /** * "offsetParent" of the component */ container: _react2['default'].PropTypes.oneOfType([_reactPropTypesLibMountable2['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']; /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _ownerDocument = __webpack_require__(164); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _domHelpersQueryOffset = __webpack_require__(227); var _domHelpersQueryOffset2 = _interopRequireDefault(_domHelpersQueryOffset); var _domHelpersQueryPosition = __webpack_require__(228); var _domHelpersQueryPosition2 = _interopRequireDefault(_domHelpersQueryPosition); var _domHelpersQueryScrollTop = __webpack_require__(230); var _domHelpersQueryScrollTop2 = _interopRequireDefault(_domHelpersQueryScrollTop); var utils = { getContainerDimensions: function getContainerDimensions(containerNode) { var width = undefined, height = undefined, scroll = undefined; if (containerNode.tagName === 'BODY') { width = window.innerWidth; height = window.innerHeight; scroll = _domHelpersQueryScrollTop2['default'](_ownerDocument2['default'](containerNode).documentElement) || _domHelpersQueryScrollTop2['default'](containerNode); } else { var _getOffset = _domHelpersQueryOffset2['default'](containerNode); width = _getOffset.width; height = _getOffset.height; scroll = _domHelpersQueryScrollTop2['default'](containerNode); } return { width: width, height: height, scroll: scroll }; }, getPosition: function getPosition(target, container) { var offset = container.tagName === 'BODY' ? _domHelpersQueryOffset2['default'](target) : _domHelpersQueryPosition2['default'](target, container); return offset; }, calcOverlayPosition: function calcOverlayPosition(placement, overlayNode, target, container, padding) { var childOffset = utils.getPosition(target, container); var _getOffset2 = _domHelpersQueryOffset2['default'](overlayNode); var overlayHeight = _getOffset2.height; var overlayWidth = _getOffset2.width; var positionLeft = undefined, positionTop = undefined, arrowOffsetLeft = undefined, arrowOffsetTop = undefined; 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 }; } }; function getTopDelta(top, overlayHeight, container, padding) { var containerDimensions = utils.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 = utils.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; } else { return 0; } } exports['default'] = utils; module.exports = exports['default']; /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var contains = __webpack_require__(85), getWindow = __webpack_require__(211), ownerDocument = __webpack_require__(84); 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; }; /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(75); exports.__esModule = true; exports['default'] = position; var _offset = __webpack_require__(227); var _offset2 = babelHelpers.interopRequireDefault(_offset); var _offsetParent = __webpack_require__(229); var _offsetParent2 = babelHelpers.interopRequireDefault(_offsetParent); var _scrollTop = __webpack_require__(230); var _scrollTop2 = babelHelpers.interopRequireDefault(_scrollTop); var _scrollLeft = __webpack_require__(231); var _scrollLeft2 = babelHelpers.interopRequireDefault(_scrollLeft); var _style = __webpack_require__(69); 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']; /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(75); exports.__esModule = true; exports['default'] = offsetParent; var _ownerDocument = __webpack_require__(84); var _ownerDocument2 = babelHelpers.interopRequireDefault(_ownerDocument); var _style = __webpack_require__(69); 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']; /***/ }, /* 230 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var getWindow = __webpack_require__(211); 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; }; /***/ }, /* 231 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var getWindow = __webpack_require__(211); 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; }; /***/ }, /* 232 */ /***/ function(module, exports, __webpack_require__) { /* eslint-disable react/prop-types */ 'use strict'; var _extends = __webpack_require__(9)['default']; var _Object$keys = __webpack_require__(28)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _domHelpersQueryContains = __webpack_require__(85); var _domHelpersQueryContains2 = _interopRequireDefault(_domHelpersQueryContains); var _lodashCompatObjectPick = __webpack_require__(169); var _lodashCompatObjectPick2 = _interopRequireDefault(_lodashCompatObjectPick); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(64); var _reactDom2 = _interopRequireDefault(_reactDom); var _warning = __webpack_require__(33); var _warning2 = _interopRequireDefault(_warning); var _Overlay = __webpack_require__(223); var _Overlay2 = _interopRequireDefault(_Overlay); var _utilsCreateChainedFunction = __webpack_require__(6); 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 OverlayTrigger = _react2['default'].createClass({ displayName: 'OverlayTrigger', propTypes: _extends({}, _Overlay2['default'].propTypes, { /** * Specify which action or actions trigger Overlay visibility */ trigger: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.oneOf(['click', 'hover', 'focus']), _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.oneOf(['click', 'hover', 'focus']))]), /** * 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, /** * The initial visibility state of the Overlay, for more nuanced visibility controll 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 */ onMouseEnter: _react2['default'].PropTypes.func, /** * @private */ onMouseLeave: _react2['default'].PropTypes.func, // override specific overlay props /** * @private */ target: function target() {}, /** * @private */ onHide: function onHide() {}, /** * @private */ show: function show() {} }), getDefaultProps: function getDefaultProps() { return { defaultOverlayShown: false, trigger: ['hover', 'focus'] }; }, getInitialState: function getInitialState() { return { isOverlayShown: this.props.defaultOverlayShown }; }, show: function show() { this.setState({ isOverlayShown: true }); }, hide: function hide() { this.setState({ isOverlayShown: false }); }, toggle: function toggle() { if (this.state.isOverlayShown) { this.hide(); } else { this.show(); } }, componentWillMount: function componentWillMount() { this.handleMouseOver = this.handleMouseOverOut.bind(null, this.handleDelayedShow); this.handleMouseOut = this.handleMouseOverOut.bind(null, this.handleDelayedHide); }, componentDidMount: function componentDidMount() { this._mountNode = document.createElement('div'); this.renderOverlay(); }, renderOverlay: function renderOverlay() { _reactDom2['default'].unstable_renderSubtreeIntoContainer(this, this._overlay, this._mountNode); }, componentWillUnmount: function componentWillUnmount() { _reactDom2['default'].unmountComponentAtNode(this._mountNode); this._mountNode = null; clearTimeout(this._hoverShowDelay); clearTimeout(this._hoverHideDelay); }, componentDidUpdate: function componentDidUpdate() { if (this._mountNode) { this.renderOverlay(); } }, getOverlayTarget: function getOverlayTarget() { return _reactDom2['default'].findDOMNode(this); }, getOverlay: function getOverlay() { var overlayProps = _extends({}, _lodashCompatObjectPick2['default'](this.props, _Object$keys(_Overlay2['default'].propTypes)), { show: this.state.isOverlayShown, onHide: this.hide, target: this.getOverlayTarget, onExit: this.props.onExit, onExiting: this.props.onExiting, onExited: this.props.onExited, onEnter: this.props.onEnter, onEntering: this.props.onEntering, onEntered: this.props.onEntered }); var overlay = _react.cloneElement(this.props.overlay, { placement: overlayProps.placement, container: overlayProps.container }); return _react2['default'].createElement( _Overlay2['default'], overlayProps, overlay ); }, render: function render() { var trigger = _react2['default'].Children.only(this.props.children); var triggerProps = trigger.props; var props = { 'aria-describedby': this.props.overlay.props.id }; // create in render otherwise owner is lost... this._overlay = this.getOverlay(); props.onClick = _utilsCreateChainedFunction2['default'](triggerProps.onClick, this.props.onClick); if (isOneOf('click', this.props.trigger)) { props.onClick = _utilsCreateChainedFunction2['default'](this.toggle, props.onClick); } if (isOneOf('hover', this.props.trigger)) { true ? _warning2['default'](!(this.props.trigger === 'hover'), '[react-bootstrap] Specifying only the `"hover"` trigger limits the visibilty 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; props.onMouseOver = _utilsCreateChainedFunction2['default'](this.handleMouseOver, this.props.onMouseOver, triggerProps.onMouseOver); props.onMouseOut = _utilsCreateChainedFunction2['default'](this.handleMouseOut, this.props.onMouseOut, triggerProps.onMouseOut); } if (isOneOf('focus', this.props.trigger)) { props.onFocus = _utilsCreateChainedFunction2['default'](this.handleDelayedShow, this.props.onFocus, triggerProps.onFocus); props.onBlur = _utilsCreateChainedFunction2['default'](this.handleDelayedHide, this.props.onBlur, triggerProps.onBlur); } return _react.cloneElement(trigger, props); }, handleDelayedShow: function handleDelayedShow() { var _this = this; if (this._hoverHideDelay != null) { clearTimeout(this._hoverHideDelay); this._hoverHideDelay = null; return; } if (this.state.isOverlayShown || 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 () { _this._hoverShowDelay = null; _this.show(); }, delay); }, handleDelayedHide: function handleDelayedHide() { var _this2 = this; if (this._hoverShowDelay != null) { clearTimeout(this._hoverShowDelay); this._hoverShowDelay = null; return; } if (!this.state.isOverlayShown || 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 () { _this2._hoverHideDelay = null; _this2.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. 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); } } }); exports['default'] = OverlayTrigger; module.exports = exports['default']; /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var PageHeader = _react2['default'].createClass({ displayName: 'PageHeader', render: function render() { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'page-header') }), _react2['default'].createElement( 'h1', null, this.props.children ) ); } }); exports['default'] = PageHeader; module.exports = exports['default']; /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _SafeAnchor = __webpack_require__(43); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var PageItem = _react2['default'].createClass({ displayName: 'PageItem', propTypes: { href: _react2['default'].PropTypes.string, target: _react2['default'].PropTypes.string, title: _react2['default'].PropTypes.string, disabled: _react2['default'].PropTypes.bool, previous: _react2['default'].PropTypes.bool, next: _react2['default'].PropTypes.bool, onSelect: _react2['default'].PropTypes.func, eventKey: _react2['default'].PropTypes.any }, getDefaultProps: function getDefaultProps() { return { disabled: false, previous: false, next: false }; }, render: function render() { var classes = { 'disabled': this.props.disabled, 'previous': this.props.previous, 'next': this.props.next }; return _react2['default'].createElement( 'li', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), _react2['default'].createElement( _SafeAnchor2['default'], { href: this.props.href, title: this.props.title, target: this.props.target, onClick: this.handleSelect }, this.props.children ) ); }, handleSelect: function handleSelect(e) { if (this.props.onSelect || this.props.disabled) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } } }); exports['default'] = PageItem; module.exports = exports['default']; /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var Pager = _react2['default'].createClass({ displayName: 'Pager', propTypes: { onSelect: _react2['default'].PropTypes.func }, render: function render() { return _react2['default'].createElement( 'ul', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'pager') }), _utilsValidComponentChildren2['default'].map(this.props.children, this.renderPageItem) ); }, renderPageItem: function renderPageItem(child, index) { return _react.cloneElement(child, { onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, this.props.onSelect), key: child.key ? child.key : index }); } }); exports['default'] = Pager; module.exports = exports['default']; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _PaginationButton = __webpack_require__(237); var _PaginationButton2 = _interopRequireDefault(_PaginationButton); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _SafeAnchor = __webpack_require__(43); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var Pagination = _react2['default'].createClass({ displayName: 'Pagination', 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'] }, getDefaultProps: function getDefaultProps() { return { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, boundaryLinks: false, buttonComponentClass: _SafeAnchor2['default'], bsClass: 'pagination' }; }, renderPageButtons: function renderPageButtons() { var pageButtons = []; var startPage = undefined, endPage = undefined, hasHiddenPagesAfter = undefined; var _props = this.props; var maxButtons = _props.maxButtons; var activePage = _props.activePage; var items = _props.items; var onSelect = _props.onSelect; var ellipsis = _props.ellipsis; var buttonComponentClass = _props.buttonComponentClass; var boundaryLinks = _props.boundaryLinks; 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'], { key: pagenumber, eventKey: pagenumber, active: pagenumber === activePage, onSelect: onSelect, buttonComponentClass: buttonComponentClass }, pagenumber )); } if (boundaryLinks && ellipsis && startPage !== 1) { pageButtons.unshift(_react2['default'].createElement( _PaginationButton2['default'], { key: 'ellipsisFirst', disabled: true, buttonComponentClass: buttonComponentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'More' }, this.props.ellipsis === true ? '…' : this.props.ellipsis ) )); pageButtons.unshift(_react2['default'].createElement( _PaginationButton2['default'], { key: 1, eventKey: 1, active: false, onSelect: onSelect, buttonComponentClass: buttonComponentClass }, '1' )); } if (maxButtons && hasHiddenPagesAfter && ellipsis) { pageButtons.push(_react2['default'].createElement( _PaginationButton2['default'], { key: 'ellipsis', disabled: true, buttonComponentClass: buttonComponentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'More' }, this.props.ellipsis === true ? '…' : this.props.ellipsis ) )); if (boundaryLinks && endPage !== items) { pageButtons.push(_react2['default'].createElement( _PaginationButton2['default'], { key: items, eventKey: items, active: false, onSelect: onSelect, buttonComponentClass: buttonComponentClass }, items )); } } return pageButtons; }, renderPrev: function renderPrev() { if (!this.props.prev) { return null; } return _react2['default'].createElement( _PaginationButton2['default'], { key: 'prev', eventKey: this.props.activePage - 1, disabled: this.props.activePage === 1, onSelect: this.props.onSelect, buttonComponentClass: this.props.buttonComponentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'Previous' }, this.props.prev === true ? '‹' : this.props.prev ) ); }, renderNext: function renderNext() { if (!this.props.next) { return null; } return _react2['default'].createElement( _PaginationButton2['default'], { key: 'next', eventKey: this.props.activePage + 1, disabled: this.props.activePage >= this.props.items, onSelect: this.props.onSelect, buttonComponentClass: this.props.buttonComponentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'Next' }, this.props.next === true ? '›' : this.props.next ) ); }, renderFirst: function renderFirst() { if (!this.props.first) { return null; } return _react2['default'].createElement( _PaginationButton2['default'], { key: 'first', eventKey: 1, disabled: this.props.activePage === 1, onSelect: this.props.onSelect, buttonComponentClass: this.props.buttonComponentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'First' }, this.props.first === true ? '«' : this.props.first ) ); }, renderLast: function renderLast() { if (!this.props.last) { return null; } return _react2['default'].createElement( _PaginationButton2['default'], { key: 'last', eventKey: this.props.items, disabled: this.props.activePage >= this.props.items, onSelect: this.props.onSelect, buttonComponentClass: this.props.buttonComponentClass }, _react2['default'].createElement( 'span', { 'aria-label': 'Last' }, this.props.last === true ? '»' : this.props.last ) ); }, render: function render() { return _react2['default'].createElement( 'ul', _extends({}, this.props, { className: _classnames2['default'](this.props.className, _utilsBootstrapUtils2['default'].getClassSet(this.props)) }), this.renderFirst(), this.renderPrev(), this.renderPageButtons(), this.renderNext(), this.renderLast() ); } }); exports['default'] = _utilsBootstrapUtils.bsClass('pagination', Pagination); module.exports = exports['default']; /***/ }, /* 237 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsCreateSelectedEvent = __webpack_require__(238); var _utilsCreateSelectedEvent2 = _interopRequireDefault(_utilsCreateSelectedEvent); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var PaginationButton = _react2['default'].createClass({ displayName: 'PaginationButton', propTypes: { className: _react2['default'].PropTypes.string, eventKey: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]), onSelect: _react2['default'].PropTypes.func, disabled: _react2['default'].PropTypes.bool, active: _react2['default'].PropTypes.bool, /** * You can use a custom element for this component */ buttonComponentClass: _reactPropTypesLibElementType2['default'] }, getDefaultProps: function getDefaultProps() { return { active: false, disabled: false }; }, handleClick: function handleClick(event) { if (this.props.disabled) { return; } if (this.props.onSelect) { var selectedEvent = _utilsCreateSelectedEvent2['default'](this.props.eventKey); this.props.onSelect(event, selectedEvent); } }, render: function render() { var classes = { active: this.props.active, disabled: this.props.disabled }; var _props = this.props; var className = _props.className; var anchorProps = _objectWithoutProperties(_props, ['className']); var ButtonComponentClass = this.props.buttonComponentClass; return _react2['default'].createElement( 'li', { className: _classnames2['default'](className, classes) }, _react2['default'].createElement(ButtonComponentClass, _extends({}, anchorProps, { onClick: this.handleClick })) ); } }); exports['default'] = PaginationButton; module.exports = exports['default']; /***/ }, /* 238 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = createSelectedEvent; function createSelectedEvent(eventKey) { var selectionPrevented = false; return { eventKey: eventKey, preventSelection: function preventSelection() { selectionPrevented = true; }, isSelectionPrevented: function isSelectionPrevented() { return selectionPrevented; } }; } module.exports = exports["default"]; /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); var _Collapse = __webpack_require__(68); var _Collapse2 = _interopRequireDefault(_Collapse); var Panel = _react2['default'].createClass({ displayName: 'Panel', 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, onEnter: _Collapse2['default'].propTypes.onEnter, onEntering: _Collapse2['default'].propTypes.onEntering, onEntered: _Collapse2['default'].propTypes.onEntered, onExit: _Collapse2['default'].propTypes.onExit, onExiting: _Collapse2['default'].propTypes.onExiting, onExited: _Collapse2['default'].propTypes.onExited }, getDefaultProps: function getDefaultProps() { return { defaultExpanded: false }; }, getInitialState: function getInitialState() { return { expanded: this.props.defaultExpanded }; }, handleSelect: function handleSelect(e) { e.selected = true; if (this.props.onSelect) { this.props.onSelect(e, this.props.eventKey); } else { e.preventDefault(); } if (e.selected) { this.handleToggle(); } }, handleToggle: function handleToggle() { this.setState({ expanded: !this.state.expanded }); }, isExpanded: function isExpanded() { return this.props.expanded != null ? this.props.expanded : this.state.expanded; }, render: function render() { var _props = this.props; var headerRole = _props.headerRole; var panelRole = _props.panelRole; var props = _objectWithoutProperties(_props, ['headerRole', 'panelRole']); return _react2['default'].createElement( 'div', _extends({}, props, { className: _classnames2['default'](this.props.className, _utilsBootstrapUtils2['default'].getClassSet(this.props)), id: this.props.collapsible ? null : this.props.id, onSelect: null }), this.renderHeading(headerRole), this.props.collapsible ? this.renderCollapsibleBody(panelRole) : this.renderBody(), this.renderFooter() ); }, renderCollapsibleBody: function renderCollapsibleBody(panelRole) { var collapseProps = { onEnter: this.props.onEnter, onEntering: this.props.onEntering, onEntered: this.props.onEntered, onExit: this.props.onExit, onExiting: this.props.onExiting, onExited: this.props.onExited, 'in': this.isExpanded() }; var props = { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'collapse'), id: this.props.id, ref: 'panel', 'aria-hidden': !this.isExpanded() }; if (panelRole) { props.role = panelRole; } return _react2['default'].createElement( _Collapse2['default'], collapseProps, _react2['default'].createElement( 'div', props, this.renderBody() ) ); }, renderBody: function renderBody() { var _this = this; var allChildren = this.props.children; var bodyElements = []; var panelBodyChildren = []; var bodyClass = _utilsBootstrapUtils2['default'].prefix(this.props, 'body'); function getProps() { return { key: bodyElements.length }; } function addPanelChild(child) { bodyElements.push(_react.cloneElement(child, getProps())); } function addPanelBody(children) { bodyElements.push(_react2['default'].createElement( 'div', _extends({ className: bodyClass }, getProps()), children )); } function maybeRenderPanelBody() { if (panelBodyChildren.length === 0) { return; } addPanelBody(panelBodyChildren); panelBodyChildren = []; } // Handle edge cases where we should not iterate through children. if (!Array.isArray(allChildren) || allChildren.length === 0) { if (this.shouldRenderFill(allChildren)) { addPanelChild(allChildren); } else { addPanelBody(allChildren); } } else { allChildren.forEach(function (child) { if (_this.shouldRenderFill(child)) { maybeRenderPanelBody(); // Separately add the filled element. addPanelChild(child); } else { panelBodyChildren.push(child); } }); maybeRenderPanelBody(); } return bodyElements; }, shouldRenderFill: function shouldRenderFill(child) { return _react2['default'].isValidElement(child) && child.props.fill != null; }, renderHeading: function renderHeading(headerRole) { var header = this.props.header; if (!header) { return null; } if (!_react2['default'].isValidElement(header) || Array.isArray(header)) { header = this.props.collapsible ? this.renderCollapsibleTitle(header, headerRole) : header; } else { var className = _classnames2['default'](_utilsBootstrapUtils2['default'].prefix(this.props, 'title'), header.props.className); if (this.props.collapsible) { header = _react.cloneElement(header, { className: className, children: this.renderAnchor(header.props.children, headerRole) }); } else { header = _react.cloneElement(header, { className: className }); } } return _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'heading') }, header ); }, renderAnchor: function renderAnchor(header, headerRole) { return _react2['default'].createElement( 'a', { href: '#' + (this.props.id || ''), 'aria-controls': this.props.collapsible ? this.props.id : null, className: this.isExpanded() ? null : 'collapsed', 'aria-expanded': this.isExpanded(), 'aria-selected': this.isExpanded(), onClick: this.handleSelect, role: headerRole }, header ); }, renderCollapsibleTitle: function renderCollapsibleTitle(header, headerRole) { return _react2['default'].createElement( 'h4', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'title'), role: 'presentation' }, this.renderAnchor(header, headerRole) ); }, renderFooter: function renderFooter() { if (!this.props.footer) { return null; } return _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'footer') }, this.props.footer ); } }); var PANEL_STATES = _styleMaps.State.values().concat(_styleMaps.DEFAULT, _styleMaps.PRIMARY); exports['default'] = _utilsBootstrapUtils.bsStyles(PANEL_STATES, _styleMaps.DEFAULT, _utilsBootstrapUtils.bsClass('panel', Panel)); module.exports = exports['default']; /***/ }, /* 240 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _reactPropTypesLibIsRequiredForA11y = __webpack_require__(155); var _reactPropTypesLibIsRequiredForA11y2 = _interopRequireDefault(_reactPropTypesLibIsRequiredForA11y); var Popover = _react2['default'].createClass({ displayName: 'Popover', 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 "left" position value for the Popover. */ positionLeft: _react2['default'].PropTypes.number, /** * The "top" position value for the Popover. */ positionTop: _react2['default'].PropTypes.number, /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: _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]), /** * Title text */ title: _react2['default'].PropTypes.node }, getDefaultProps: function getDefaultProps() { return { placement: 'right', bsClass: 'popover' }; }, render: function render() { var _classes; var classes = (_classes = {}, _classes[_utilsBootstrapUtils2['default'].prefix(this.props)] = true, _classes[this.props.placement] = true, _classes); var style = _extends({ 'left': this.props.positionLeft, 'top': this.props.positionTop, 'display': 'block' }, this.props.style); // eslint-disable-line react/prop-types var arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return _react2['default'].createElement( 'div', _extends({ role: 'tooltip' }, this.props, { className: _classnames2['default'](this.props.className, classes), style: style, title: null }), _react2['default'].createElement('div', { className: 'arrow', style: arrowStyle }), this.props.title ? this.renderTitle() : null, _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'content') }, this.props.children ) ); }, renderTitle: function renderTitle() { return _react2['default'].createElement( 'h3', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'title') }, this.props.title ); } }); exports['default'] = Popover; module.exports = exports['default']; // we don't want to expose the `style` property /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Interpolate = __webpack_require__(175); var _Interpolate2 = _interopRequireDefault(_Interpolate); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); /** * Custom propTypes checker */ function onlyProgressBar(props, propName, componentName) { if (props[propName]) { var _ret = (function () { var error = undefined, childIdentifier = undefined; _react2['default'].Children.forEach(props[propName], function (child) { if (child.type !== ProgressBar) { //eslint-disable-line childIdentifier = child.type.displayName ? child.type.displayName : child.type; error = new Error('Children of ' + componentName + ' can contain only ProgressBar components. Found ' + childIdentifier); } }); return { v: error }; })(); if (typeof _ret === 'object') return _ret.v; } } var ProgressBar = (function (_React$Component) { _inherits(ProgressBar, _React$Component); function ProgressBar() { _classCallCheck(this, ProgressBar); _React$Component.apply(this, arguments); } ProgressBar.prototype.getPercentage = function getPercentage(now, min, max) { var roundPrecision = 1000; return Math.round((now - min) / (max - min) * 100 * roundPrecision) / roundPrecision; }; ProgressBar.prototype.render = function render() { if (this.props.isChild) { return this.renderProgressBar(); } var content = undefined; if (this.props.children) { content = _utilsValidComponentChildren2['default'].map(this.props.children, this.renderChildBar); } else { content = this.renderProgressBar(); } return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'progress'), min: null, max: null, label: null, 'aria-valuetext': null }), content ); }; ProgressBar.prototype.renderChildBar = function renderChildBar(child, index) { return _react.cloneElement(child, { isChild: true, key: child.key ? child.key : index }); }; ProgressBar.prototype.renderProgressBar = function renderProgressBar() { var _classNames; var _props = this.props; var className = _props.className; var label = _props.label; var now = _props.now; var min = _props.min; var max = _props.max; var props = _objectWithoutProperties(_props, ['className', 'label', 'now', 'min', 'max']); var percentage = this.getPercentage(now, min, max); if (typeof label === 'string') { label = this.renderLabel(percentage); } if (this.props.srOnly) { label = _react2['default'].createElement( 'span', { className: 'sr-only' }, label ); } var classes = _classnames2['default'](className, _utilsBootstrapUtils2['default'].getClassSet(this.props), (_classNames = { active: this.props.active }, _classNames[_utilsBootstrapUtils2['default'].prefix(this.props, 'striped')] = this.props.active || this.props.striped, _classNames)); return _react2['default'].createElement( 'div', _extends({}, props, { className: classes, role: 'progressbar', style: { width: percentage + '%' }, 'aria-valuenow': this.props.now, 'aria-valuemin': this.props.min, 'aria-valuemax': this.props.max }), label ); }; ProgressBar.prototype.renderLabel = function renderLabel(percentage) { var InterpolateClass = this.props.interpolateClass || _Interpolate2['default']; return _react2['default'].createElement( InterpolateClass, { now: this.props.now, min: this.props.min, max: this.props.max, percent: percentage, bsStyle: this.props.bsStyle }, this.props.label ); }; return ProgressBar; })(_react2['default'].Component); ProgressBar.propTypes = _extends({}, ProgressBar.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, className: _react2['default'].PropTypes.string, interpolateClass: _react.PropTypes.node, /** * @private */ isChild: _react.PropTypes.bool }); ProgressBar.defaultProps = _extends({}, ProgressBar.defaultProps, { min: 0, max: 100, active: false, isChild: false, srOnly: false, striped: false }); exports['default'] = _utilsBootstrapUtils.bsStyles(_styleMaps.State.values(), _utilsBootstrapUtils.bsClass('progress-bar', ProgressBar)); module.exports = exports['default']; /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(33); var _warning2 = _interopRequireDefault(_warning); 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 _props = this.props; var bsClass = _props.bsClass; var className = _props.className; var a16by9 = _props.a16by9; var a4by3 = _props.a4by3; var children = _props.children; var props = _objectWithoutProperties(_props, ['bsClass', 'className', 'a16by9', 'a4by3', 'children']); true ? _warning2['default'](!(!a16by9 && !a4by3), '`a16by9` or `a4by3` attribute must be set.') : undefined; true ? _warning2['default'](!(a16by9 && a4by3), 'Either `a16by9` or `a4by3` attribute can be set. Not both.') : undefined; var aspectRatio = { 'embed-responsive-16by9': a16by9, 'embed-responsive-4by3': a4by3 }; return _react2['default'].createElement( 'div', { className: _classnames2['default'](bsClass, aspectRatio) }, _react.cloneElement(children, _extends({}, props, { className: _classnames2['default'](className, 'embed-responsive-item') })) ); }; return ResponsiveEmbed; })(_react2['default'].Component); ResponsiveEmbed.defaultProps = { bsClass: 'embed-responsive', a16by9: false, a4by3: false }; ResponsiveEmbed.propTypes = { /** * bootstrap className * @private */ bsClass: _react.PropTypes.string, /** * This component accepts only one child element */ children: _react.PropTypes.element.isRequired, /** * 16by9 aspect ratio */ a16by9: _react.PropTypes.bool, /** * 4by3 aspect ratio */ a4by3: _react.PropTypes.bool }; exports['default'] = ResponsiveEmbed; module.exports = exports['default']; /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var Row = _react2['default'].createClass({ displayName: 'Row', propTypes: { /** * You can use a custom element for this component */ componentClass: _reactPropTypesLibElementType2['default'] }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, render: function render() { var ComponentClass = this.props.componentClass; return _react2['default'].createElement( ComponentClass, _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'row') }), this.props.children ); } }); exports['default'] = Row; module.exports = exports['default']; /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _Object$keys = __webpack_require__(28)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Button = __webpack_require__(52); var _Button2 = _interopRequireDefault(_Button); var _Dropdown = __webpack_require__(82); var _Dropdown2 = _interopRequireDefault(_Dropdown); var _SplitToggle = __webpack_require__(245); var _SplitToggle2 = _interopRequireDefault(_SplitToggle); var _lodashCompatObjectOmit = __webpack_require__(140); var _lodashCompatObjectOmit2 = _interopRequireDefault(_lodashCompatObjectOmit); var _lodashCompatObjectPick = __webpack_require__(169); var _lodashCompatObjectPick2 = _interopRequireDefault(_lodashCompatObjectPick); 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 children = _props.children; var title = _props.title; var onClick = _props.onClick; var target = _props.target; var href = _props.href; var toggleLabel = _props.toggleLabel; var bsSize = _props.bsSize; var bsStyle = _props.bsStyle; var props = _objectWithoutProperties(_props, ['children', 'title', 'onClick', 'target', 'href', 'toggleLabel', 'bsSize', 'bsStyle']); var disabled = props.disabled; var dropdownProps = _lodashCompatObjectPick2['default'](props, _Object$keys(_Dropdown2['default'].ControlledComponent.propTypes)); var buttonProps = _lodashCompatObjectOmit2['default'](props, _Object$keys(_Dropdown2['default'].ControlledComponent.propTypes)); return _react2['default'].createElement( _Dropdown2['default'], dropdownProps, _react2['default'].createElement( _Button2['default'], _extends({}, buttonProps, { onClick: onClick, bsStyle: bsStyle, bsSize: bsSize, disabled: disabled, target: target, href: href }), title ), _react2['default'].createElement(_SplitToggle2['default'], { 'aria-label': toggleLabel || title, bsStyle: bsStyle, bsSize: bsSize, disabled: disabled }), _react2['default'].createElement( _Dropdown2['default'].Menu, null, children ) ); }; return SplitButton; })(_react2['default'].Component); SplitButton.propTypes = _extends({}, _Dropdown2['default'].propTypes, { bsStyle: _Button2['default'].propTypes.bsStyle, /** * @private */ onClick: function onClick() {}, target: _react2['default'].PropTypes.string, href: _react2['default'].PropTypes.string, /** * 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 }); SplitButton.defaultProps = { disabled: false, dropup: false, pullRight: false }; SplitButton.Toggle = _SplitToggle2['default']; exports['default'] = SplitButton; module.exports = exports['default']; /***/ }, /* 245 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _DropdownToggle = __webpack_require__(165); 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); exports['default'] = SplitToggle; SplitToggle.defaultProps = _DropdownToggle2['default'].defaultProps; module.exports = exports['default']; /***/ }, /* 246 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _TabPane = __webpack_require__(247); var _TabPane2 = _interopRequireDefault(_TabPane); var _TabContainer = __webpack_require__(248); var _TabContainer2 = _interopRequireDefault(_TabContainer); var _TabContent = __webpack_require__(249); var _TabContent2 = _interopRequireDefault(_TabContent); 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 = this.props; var title = _props.title; var disabled = _props.disabled; var tabClassName = _props.tabClassName; var props = _objectWithoutProperties(_props, ['title', 'disabled', 'tabClassName']); return _react2['default'].createElement(_TabPane2['default'], props); }; return Tab; })(_react2['default'].Component); Tab.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 }); Tab.Container = _TabContainer2['default']; Tab.Content = _TabContent2['default']; Tab.Pane = _TabPane2['default']; exports['default'] = Tab; module.exports = exports['default']; /***/ }, /* 247 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _warning = __webpack_require__(33); var _warning2 = _interopRequireDefault(_warning); var _Fade = __webpack_require__(193); var _Fade2 = _interopRequireDefault(_Fade); var _domHelpersClassAddClass = __webpack_require__(207); var _domHelpersClassAddClass2 = _interopRequireDefault(_domHelpersClassAddClass); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsCreateChainedFunction = __webpack_require__(6); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _utilsTabUtils = __webpack_require__(215); var TabPane = _react2['default'].createClass({ displayName: 'TabPane', propTypes: { /** * Uniquely identify the TabPane amoung its siblings. */ eventKey: _react.PropTypes.any, /** * Use animation when showing or hiding TabPanes. 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, /** * 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 }, contextTypes: { $bs_tabcontainer: _react.PropTypes.shape({ getId: _react.PropTypes.func }), $bs_tabcontent: _react.PropTypes.shape({ bsClass: _react.PropTypes.string, animation: _react.PropTypes.oneOfType([_react.PropTypes.bool, _reactPropTypesLibElementType2['default']]), activeKey: _react.PropTypes.any, onExited: _react.PropTypes.func, register: _react.PropTypes.func }) }, /** * We override the TabContainer context so Navs in TabPanes * don't conflict with the top level one. */ childContextTypes: { $bs_tabcontainer: _react.PropTypes.oneOf([null]) }, componentWillMount: function componentWillMount() { this.exited = !this.isActive(); this.registerWithParent(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps, nextContext) { if (nextProps.eventKey !== this.props.eventKey) { this.unregisterWithParent(); this.registerWithParent(nextProps, nextContext); } }, componentWillUpdate: function componentWillUpdate(nextProps, _, nextContext) { if (this.isActive(nextProps, nextContext)) { this.exited = false; } else if (!this.exited && !this.getTransition(nextProps, nextContext)) { // Otherwise let handleHidden take care of marking exited. this.exited = true; this._fireExitedCallback = true; } }, componentDidUpdate: function componentDidUpdate() { if (this._fireExitedCallback) { this._fireExitedCallback = false; this.onExited(); } }, componentWillUnmount: function componentWillUnmount() { this.unregisterWithParent(); }, getChildContext: function getChildContext() { return { $bs_tabcontainer: null }; }, getTransition: function getTransition() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var context = arguments.length <= 1 || arguments[1] === undefined ? this.context : arguments[1]; context = this.getContext('$bs_tabcontent', context); return props.animation != null ? props.animation : context.animation; }, isActive: function isActive() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var context = arguments.length <= 1 || arguments[1] === undefined ? this.context : arguments[1]; return this.getContext('$bs_tabcontent', context).activeKey === props.eventKey; }, render: function render() { var _classes; var active = this.isActive(); var visible = active || !this.exited; var getId = this.getContext('$bs_tabcontainer').getId; var bsClass = this.props.bsClass || this.getContext('$bs_tabcontent').bsClass; var Transition = this.getTransition(); var classes = (_classes = { active: visible }, _classes[_utilsBootstrapUtils2['default'].prefix({ bsClass: bsClass }, 'pane')] = true, _classes); var _props = this.props; var eventKey = _props.eventKey; var id = _props.id; var labelledBy = _props['aria-labelledby']; var onExit = _props.onExit; var onExiting = _props.onExiting; var onExited = _props.onExited; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; if (typeof Transition === 'boolean') { Transition = Transition ? _Fade2['default'] : null; } if (getId) { true ? _warning2['default'](!(id || 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; id = getId(eventKey, _utilsTabUtils.PANE) || null; labelledBy = getId(eventKey, _utilsTabUtils.TAB) || null; } var tabPane = _react2['default'].createElement( 'div', _extends({}, this.props, { id: id, role: 'tabpanel', 'aria-hidden': !visible, 'aria-labelledby': labelledBy, className: _classnames2['default'](this.props.className, classes, { 'in': !Transition }) }), this.props.children ); if (Transition) { tabPane = _react2['default'].createElement( Transition, { 'in': active, onExit: onExit, onExiting: onExiting, onExited: _utilsCreateChainedFunction2['default'](this.handleExited, onExited), onEnter: _utilsCreateChainedFunction2['default'](this.handleEnter, onEnter), onEntering: onEntering, onEntered: onEntered }, tabPane ); } return tabPane; }, onExited: function onExited() { var context = this.getContext('$bs_tabcontent'); if (context.onExited) { context.onExited(this.props.eventKey); } }, handleEnter: function handleEnter(node) { // ref: https://github.com/react-bootstrap/react-overlays/issues/40 if (this.isActive()) { _domHelpersClassAddClass2['default'](node, 'active'); node.offsetWidth; // eslint-disable-line no-unused-expressions } }, handleExited: function handleExited() { this.exited = true; this.onExited(); this.forceUpdate(); }, registerWithParent: function registerWithParent() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var context = arguments.length <= 1 || arguments[1] === undefined ? this.context : arguments[1]; var register = this.getContext('$bs_tabcontent', context).register; if (register) { this.unregister = register(props.eventKey); } }, unregisterWithParent: function unregisterWithParent() { if (this.unregister) { this.unregister(); } }, getContext: function getContext(key) { var context = arguments.length <= 1 || arguments[1] === undefined ? this.context : arguments[1]; return context[key] || {}; } }); exports['default'] = _utilsBootstrapUtils.bsClass('tab', TabPane); module.exports = exports['default']; /***/ }, /* 248 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _objectWithoutProperties = __webpack_require__(36)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _uncontrollable = __webpack_require__(156); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var idPropType = _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]); var TabContainer = _react2['default'].createClass({ displayName: 'TabContainer', 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 inialize 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 NavItems and TabPanes. 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 }, childContextTypes: { $bs_tabcontainer: _react2['default'].PropTypes.shape({ activeKey: _react.PropTypes.any, onSelect: _react.PropTypes.func, getId: _react.PropTypes.func }) }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, getChildContext: function getChildContext() { var _this = this; return { $bs_tabcontainer: { activeKey: this.props.activeKey, onSelect: this.props.onSelect, getId: this.props.generateChildId || function (key, type) { return _this.props.id ? _this.props.id + '-' + type + '-' + key : null; } } }; }, render: function render() { var _props = this.props; var children = _props.children; var props = _objectWithoutProperties(_props, ['children']); return _react2['default'].cloneElement(_react2['default'].Children.only(children), props); } }); exports['default'] = _uncontrollable2['default'](TabContainer, { activeKey: 'onSelect' }); module.exports = exports['default']; /***/ }, /* 249 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _invariant = __webpack_require__(32); var _invariant2 = _interopRequireDefault(_invariant); var _reactPropTypesLibElementType = __webpack_require__(53); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var animationPropType = _react.PropTypes.oneOfType([_react.PropTypes.bool, _reactPropTypesLibElementType2['default']]); var TabContent = _react2['default'].createClass({ displayName: 'TabContent', propTypes: { /** * the Component used to render the TabContent */ componentClass: _reactPropTypesLibElementType2['default'], /** * Sets a default animation strategy for all children TabPanes. * Use `false` to disable, `true` to enable the default "Fade" * animation or any `<Transition>` component. */ animation: _react.PropTypes.oneOfType([_react.PropTypes.bool, _reactPropTypesLibElementType2['default']]) }, contextTypes: { $bs_tabcontainer: _react2['default'].PropTypes.shape({ activeKey: _react2['default'].PropTypes.any, onSelect: _react.PropTypes.func }) }, childContextTypes: { $bs_tabcontent: _react.PropTypes.shape({ bsClass: _react.PropTypes.string, animation: animationPropType, activeKey: _react.PropTypes.any, onExited: _react.PropTypes.func, register: _react.PropTypes.func }) }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div', animation: true }; }, getInitialState: function getInitialState() { return { exitingPane: null }; }, getChildContext: function getChildContext() { var exitingPane = this._exitingPane; return { $bs_tabcontent: { bsClass: this.props.bsClass, animation: this.props.animation, activeKey: exitingPane ? undefined : this.getActiveKey(), onExited: this.handlePaneExited, register: this.registerPane } }; }, /** * This belongs in `componentWillReceiveProps()` but * 0.14.x contains a bug where cwrp isn't called when only context changes. * fixed in master, not sure it will make it into any 0.14 release */ componentWillUpdate: function componentWillUpdate(nextProps, _, nextContext) { var currentActiveKey = this.getActiveKey(); var nextActiveKey = this.getActiveKey(nextContext); var currentKeyIsStillValid = this.panes.indexOf(currentActiveKey) !== -1; if (this.panes.indexOf(this._exitingPane) === -1) { this._exitingPane = null; } if (nextActiveKey !== currentActiveKey && currentKeyIsStillValid) { this._exitingPane = currentActiveKey; } }, render: function render() { var _props = this.props; var className = _props.className; var children = _props.children; var Component = this.props.componentClass; var contentClass = _utilsBootstrapUtils2['default'].prefix(this.props, 'content'); return _react2['default'].createElement( Component, { className: _classnames2['default'](contentClass, className) }, children ); }, handlePaneExited: function handlePaneExited() { this._exitingPane = null; this.forceUpdate(); }, /** * This is unfortunately neccessary because the TabContent needs to know if * a TabPane is ever going to exit, since it may unmount and just leave the * TabContent to wait longingly forever for the handlePaneExited to be called. */ registerPane: function registerPane(eventKey) { var _this = this; var panes = this.panes || (this.panes = []); !(panes.indexOf(eventKey) === -1) ? true ? _invariant2['default'](false, 'You cannot have multiple TabPanes of with the same `eventKey` in the same ' + 'TabContent component. Duplicate eventKey: ' + eventKey) : _invariant2['default'](false) : undefined; panes.push(eventKey); return function () { panes.splice(panes.indexOf(eventKey), 1); if (eventKey === _this.getActiveKey()) { _this.getContext('$bs_tabcontainer').onSelect(); } }; }, getActiveKey: function getActiveKey() { var context = arguments.length <= 0 || arguments[0] === undefined ? this.context : arguments[0]; return this.getContext('$bs_tabcontainer', context).activeKey; }, getContext: function getContext(key) { var context = arguments.length <= 1 || arguments[1] === undefined ? this.context : arguments[1]; return context[key] || {}; } }); exports['default'] = _utilsBootstrapUtils.bsClass('tab', TabContent); module.exports = exports['default']; /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var Table = _react2['default'].createClass({ displayName: 'Table', 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 }, getDefaultProps: function getDefaultProps() { return { bordered: false, condensed: false, hover: false, responsive: false, striped: false }; }, render: function render() { var classes = { 'table': true, 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed, 'table-hover': this.props.hover }; var table = _react2['default'].createElement( 'table', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.children ); return this.props.responsive ? _react2['default'].createElement( 'div', { className: 'table-responsive' }, table ) : table; } }); exports['default'] = Table; module.exports = exports['default']; /***/ }, /* 251 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _objectWithoutProperties = __webpack_require__(36)['default']; var _Object$keys = __webpack_require__(28)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _uncontrollable = __webpack_require__(156); var _uncontrollable2 = _interopRequireDefault(_uncontrollable); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _Col = __webpack_require__(66); var _Col2 = _interopRequireDefault(_Col); var _Nav = __webpack_require__(214); var _Nav2 = _interopRequireDefault(_Nav); var _NavItem = __webpack_require__(222); var _NavItem2 = _interopRequireDefault(_NavItem); var _styleMaps = __webpack_require__(25); var _styleMaps2 = _interopRequireDefault(_styleMaps); var _reactPropTypesLibIsRequiredForA11y = __webpack_require__(155); var _reactPropTypesLibIsRequiredForA11y2 = _interopRequireDefault(_reactPropTypesLibIsRequiredForA11y); var _utilsDeprecationWarning = __webpack_require__(81); var _utilsDeprecationWarning2 = _interopRequireDefault(_utilsDeprecationWarning); var _utilsValidComponentChildren = __webpack_require__(7); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _TabContainer = __webpack_require__(248); var _TabContainer2 = _interopRequireDefault(_TabContainer); var _TabContent = __webpack_require__(249); var _TabContent2 = _interopRequireDefault(_TabContent); var TabContainer = _TabContainer2['default'].ControlledComponent; function getDefaultActiveKeyFromChildren(children) { var defaultActiveKey = undefined; _utilsValidComponentChildren2['default'].forEach(children, function (child) { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } var Tabs = _react2['default'].createClass({ displayName: 'Tabs', propTypes: { /** * Mark the Tab with a matching `eventKey` as active. * * @controllable onSelect */ activeKey: _react2['default'].PropTypes.any, /** * Navigation style for tabs * * If not specified, it will be treated as `'tabs'` when vertically * positioned and `'pills'` when horizontally positioned. */ 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, /** * @deprecated Use TabContainer to create differently shaped tab layouts. */ position: _react2['default'].PropTypes.oneOf(['top', 'left', 'right']), /** * Number of grid columns for the tabs if horizontally positioned * * This accepts either a single width or a mapping of size to width. * * @deprecated Use TabContainer to create differently shaped tab layouts. */ tabWidth: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.object]), /** * Number of grid columns for the panes if horizontally positioned * * This accepts either a single width or a mapping of size to width. If not * specified, it will be treated as `styleMaps.GRID_COLUMNS` minus * `tabWidth`. * * @deprecated Use TabContainer to create differently shaped tab layouts. */ paneWidth: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.object]), /** * Render without clearfix if horizontally positioned * * @deprecated Use TabContainer to create differently shaped tab layouts. */ standalone: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { bsClass: 'tab', animation: true, tabWidth: 2, position: 'top', standalone: false }; }, render: function render() { var _props = this.props; var id = _props.id; var className = _props.className; var style = _props.style; var position = _props.position; var bsStyle = _props.bsStyle; var tabWidth = _props.tabWidth; var paneWidth = _props.paneWidth; var standalone = _props.standalone; var children = _props.children; var onSelect = _props.onSelect; var activeKey = _props.activeKey; var props = _objectWithoutProperties(_props, ['id', 'className', 'style', 'position', 'bsStyle', 'tabWidth', 'paneWidth', 'standalone', 'children', 'onSelect', 'activeKey']); activeKey = this.getActiveKey(); var isHorizontal = position === 'left' || position === 'right'; if (bsStyle == null) { bsStyle = isHorizontal ? 'pills' : 'tabs'; } var containerProps = { id: id, className: className, style: style, activeKey: activeKey, onSelect: onSelect }; var tabsProps = _extends({}, props, { bsStyle: bsStyle, bsClass: undefined, stacked: isHorizontal, ref: 'tabs', role: 'tablist' }); var childTabs = _utilsValidComponentChildren2['default'].map(children, this.renderTab); var panesProps = { ref: 'panes', animation: props.animation }; var childPanes = children; if (isHorizontal) { _utilsDeprecationWarning2['default']({ message: 'Horizontal Tabs (position "left" or "right") are deprecated in favor ' + 'of the more flexible TabContainer component.' }); if (!standalone) { containerProps.className = _classnames2['default'](containerProps.className, 'clearfix'); } var _getColProps = this.getColProps({ tabWidth: tabWidth, paneWidth: paneWidth }); var tabsColProps = _getColProps.tabsColProps; var panesColProps = _getColProps.panesColProps; var tabs = _react2['default'].createElement( _Col2['default'], _extends({ componentClass: _Nav2['default'] }, tabsProps, tabsColProps), childTabs ); var panes = _react2['default'].createElement( _Col2['default'], _extends({ componentClass: _TabContent2['default'] }, panesProps, panesColProps), childPanes ); if (position === 'left') { return _react2['default'].createElement( TabContainer, containerProps, _react2['default'].createElement( 'div', containerProps, tabs, panes ) ); } return _react2['default'].createElement( TabContainer, containerProps, _react2['default'].createElement( 'div', containerProps, panes, tabs ) ); } return _react2['default'].createElement( TabContainer, containerProps, _react2['default'].createElement( 'div', containerProps, _react2['default'].createElement( _Nav2['default'], tabsProps, childTabs ), _react2['default'].createElement( _TabContent2['default'], panesProps, childPanes ) ) ); }, getActiveKey: function getActiveKey() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var activeKey = props.activeKey; var children = props.children; return activeKey === undefined ? getDefaultActiveKeyFromChildren(children) : activeKey; }, renderPane: function renderPane(child, index) { return _react.cloneElement(child, { key: child.key ? child.key : index }); }, renderTab: function renderTab(child) { if (child.props.title == null) { return null; } var _child$props = child.props; var eventKey = _child$props.eventKey; var title = _child$props.title; var disabled = _child$props.disabled; var tabClassName = _child$props.tabClassName; return _react2['default'].createElement( _NavItem2['default'], { eventKey: eventKey, disabled: disabled, className: tabClassName }, title ); }, getColProps: function getColProps(_ref) { var tabWidth = _ref.tabWidth; var paneWidth = _ref.paneWidth; var tabsColProps = undefined; if (tabWidth instanceof Object) { tabsColProps = tabWidth; } else { tabsColProps = { xs: tabWidth }; } var panesColProps = undefined; if (paneWidth == null) { panesColProps = {}; _Object$keys(tabsColProps).forEach(function (size) { panesColProps[size] = _styleMaps2['default'].GRID_COLUMNS - tabsColProps[size]; }); } else if (paneWidth instanceof Object) { panesColProps = paneWidth; } else { panesColProps = { xs: paneWidth }; } return { tabsColProps: tabsColProps, panesColProps: panesColProps }; } }); exports['default'] = _uncontrollable2['default'](Tabs, { activeKey: 'onSelect' }); module.exports = exports['default']; /***/ }, /* 252 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _SafeAnchor = __webpack_require__(43); var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var Thumbnail = _react2['default'].createClass({ displayName: 'Thumbnail', propTypes: { alt: _react2['default'].PropTypes.string, href: _react2['default'].PropTypes.string, src: _react2['default'].PropTypes.string }, render: function render() { var classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); if (this.props.href) { return _react2['default'].createElement( _SafeAnchor2['default'], _extends({}, this.props, { href: this.props.href, className: _classnames2['default'](this.props.className, classes) }), _react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt }) ); } if (this.props.children) { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), _react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt }), _react2['default'].createElement( 'div', { className: 'caption' }, this.props.children ) ); } return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), _react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt }) ); } }); exports['default'] = _utilsBootstrapUtils.bsClass('thumbnail', Thumbnail); module.exports = exports['default']; /***/ }, /* 253 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _reactPropTypesLibIsRequiredForA11y = __webpack_require__(155); var _reactPropTypesLibIsRequiredForA11y2 = _interopRequireDefault(_reactPropTypesLibIsRequiredForA11y); var Tooltip = _react2['default'].createClass({ displayName: 'Tooltip', 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 Tooltip is positioned towards. */ placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "left" position value for the Tooltip. */ positionLeft: _react2['default'].PropTypes.number, /** * The "top" position value for the Tooltip. */ positionTop: _react2['default'].PropTypes.number, /** * The "left" position value for the Tooltip arrow. */ arrowOffsetLeft: _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]), /** * Title text */ title: _react2['default'].PropTypes.node }, getDefaultProps: function getDefaultProps() { return { bsClass: 'tooltip', placement: 'right' }; }, render: function render() { var _classes; var classes = (_classes = {}, _classes[_utilsBootstrapUtils2['default'].prefix(this.props)] = true, _classes[this.props.placement] = true, _classes); var style = _extends({ 'left': this.props.positionLeft, 'top': this.props.positionTop }, this.props.style); var arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return _react2['default'].createElement( 'div', _extends({ role: 'tooltip' }, this.props, { className: _classnames2['default'](this.props.className, classes), style: style }), _react2['default'].createElement('div', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'arrow'), style: arrowStyle }), _react2['default'].createElement( 'div', { className: _utilsBootstrapUtils2['default'].prefix(this.props, 'inner') }, this.props.children ) ); } }); exports['default'] = Tooltip; module.exports = exports['default']; /***/ }, /* 254 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _inherits = __webpack_require__(44)['default']; var _classCallCheck = __webpack_require__(51)['default']; var _extends = __webpack_require__(9)['default']; var _interopRequireDefault = __webpack_require__(1)['default']; exports.__esModule = true; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(37); var _classnames2 = _interopRequireDefault(_classnames); var _utilsBootstrapUtils = __webpack_require__(8); var _utilsBootstrapUtils2 = _interopRequireDefault(_utilsBootstrapUtils); var _styleMaps = __webpack_require__(25); 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 classes = _utilsBootstrapUtils2['default'].getClassSet(this.props); return _react2['default'].createElement( 'div', _extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }), this.props.children ); }; var _Well = Well; Well = _utilsBootstrapUtils.bsSizes([_styleMaps.Sizes.LARGE, _styleMaps.Sizes.SMALL])(Well) || Well; Well = _utilsBootstrapUtils.bsClass('well')(Well) || Well; return Well; })(_react2['default'].Component); exports['default'] = Well; module.exports = exports['default']; /***/ } /******/ ]) }); ;
src/app/screens/App/screens/Dashboard/components/Dashboard.js
docgecko/react-alt-firebase-starter
/*! React Alt Firebase Starter */ import './Dashboard.less'; import React from 'react'; export default class Dashboard extends React.Component { render() { return ( <div className='dashboard'> <h1>Welcome to the Dashboard...</h1> </div> ); } }
tools/start.js
kareems/tax-receipt
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import browserSync from 'browser-sync'; import webpack from 'webpack'; import hygienistMiddleware from 'hygienist-middleware'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; global.watch = true; const webpackConfig = require('./webpack.config')[0]; const bundler = webpack(webpackConfig); export default async () => { await require('./build')(); browserSync({ server: { baseDir: 'build', middleware: [ hygienistMiddleware('build'), webpackDevMiddleware(bundler, { // IMPORTANT: dev middleware can't access config, so we should // provide publicPath by ourselves publicPath: webpackConfig.output.publicPath, // pretty colored output stats: webpackConfig.stats, // for other settings see // http://webpack.github.io/docs/webpack-dev-middleware.html }), // bundler should be the same as above webpackHotMiddleware(bundler), ], }, // no need to watch '*.js' here, webpack will take care of it for us, // including full page reloads if HMR won't work files: [ 'build/**/*.css', 'build/**/*.html', ], }); };
src/routes.js
mikeyhogarth/nasteroids
import React from 'react'; import { Router, Route, IndexRoute, hashHistory } from 'react-router'; import App from './components/app/app.component'; import Asteroids from './components/asteroids/asteroids.component'; import Asteroid from './components/asteroid/asteroid.component'; import About from './components/about/about.component'; import NotFound from './components/not-found/not-found.component'; const Routes = (props) => ( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Asteroids} /> <Route path="/asteroids" component={Asteroids} /> <Route path="/asteroid/:neo_reference_id" component={Asteroid} /> <Route path="/about" component={About} /> </Route> <Route path="*" component={NotFound} /> </Router> ); export default Routes;
src/components/Group.js
dialob/dialob-fill-ui
/** * Copyright 2016 ReSys OÜ * * 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 classnames from 'classnames'; import ReactMarkdown from 'react-markdown'; import PropTypes from 'prop-types'; export default class Group extends React.Component { static get propTypes() { return { group: PropTypes.array.isRequired }; } static get contextTypes() { return { componentCreator: PropTypes.func.isRequired }; } renderDescription() { if (this.props.group[1].get('description')) { return ( <div className='dialob-description'> <ReactMarkdown source={this.props.group[1].get('description')} escapeHtml={true} /> </div> ) } else { return null; } } render() { let group = this.props.group && this.props.group[1]; if (!group) { return null; } let className = group.get('className'); let customStyles = []; if (className) { customStyles = className.toJS(); } let title = group.get('label'); let questions = group.get('items').toJS() .map(this.context.componentCreator) .filter(question => question); return ( <div className={classnames('dialob-group', customStyles)}> <span className='dialob-group-title'>{title}</span> { this.renderDescription() } {questions} </div> ); } }
lib/SevenHour.js
danalvarez5280/Weatherly
import React from 'react'; import Card from './Card'; export default function SevenHour (props) { const hourlyInfo = props.sevenHourInfo.slice(0, 6) return ( <div className="hourly-forecast"> The 7 Hour Forecast <div className="seven-hour"> { hourlyInfo.map(obj => { return ( <Card time={obj.FCTTIME.civil} condition={obj.condition} temp={obj.temp.english} icon={obj.icon} /> ); }) } </div> </div> ); }
node_modules/react-bootstrap/es/FormGroup.js
CallumRocks/ReduxSimpleStarter
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 classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { bsClass, bsSizes, getClassSet, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import { Size } from './utils/StyleConfig'; import ValidComponentChildren from './utils/ValidComponentChildren'; var propTypes = { /** * Sets `id` on `<FormControl>` and `htmlFor` on `<FormGroup.Label>`. */ controlId: PropTypes.string, validationState: PropTypes.oneOf(['success', 'warning', 'error', null]) }; var childContextTypes = { $bs_formGroup: PropTypes.object.isRequired }; var FormGroup = function (_React$Component) { _inherits(FormGroup, _React$Component); function FormGroup() { _classCallCheck(this, FormGroup); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } FormGroup.prototype.getChildContext = function getChildContext() { var _props = this.props, controlId = _props.controlId, validationState = _props.validationState; return { $bs_formGroup: { controlId: controlId, validationState: validationState } }; }; FormGroup.prototype.hasFeedback = function hasFeedback(children) { var _this2 = this; return ValidComponentChildren.some(children, function (child) { return child.props.bsRole === 'feedback' || child.props.children && _this2.hasFeedback(child.props.children); }); }; FormGroup.prototype.render = function render() { var _props2 = this.props, validationState = _props2.validationState, className = _props2.className, children = _props2.children, props = _objectWithoutProperties(_props2, ['validationState', 'className', 'children']); var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['controlId']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; var classes = _extends({}, getClassSet(bsProps), { 'has-feedback': this.hasFeedback(children) }); if (validationState) { classes['has-' + validationState] = true; } return React.createElement( 'div', _extends({}, elementProps, { className: classNames(className, classes) }), children ); }; return FormGroup; }(React.Component); FormGroup.propTypes = propTypes; FormGroup.childContextTypes = childContextTypes; export default bsClass('form-group', bsSizes([Size.LARGE, Size.SMALL], FormGroup));
icons/communication/stay-primary-portrait.js
mikamaunula/react-material-icons
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var createClass = require('create-react-class'); var CommunicationStayPrimaryPortrait = createClass({ displayName: 'CommunicationStayPrimaryPortrait', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M17 1.01L7 1c-1.1 0-1.99.9-1.99 2v18c0 1.1.89 2 1.99 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z' }) ); } }); module.exports = CommunicationStayPrimaryPortrait;
src/routes/contact/index.js
ben-miller/adddr.io
/** * adddr (https://www.adddr.io/) * * 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 Layout from '../../components/Layout'; import Contact from './Contact'; const title = 'Contact Us'; function action() { return { chunks: ['contact'], title, component: ( <Layout> <Contact title={title} /> </Layout> ), }; } export default action;
app/config/routes.js
ldd/samosa-search
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import Main from '../components/Main/Main'; import Sale from '../components/Sale/Sale'; import SaleMap from '../components/MapView/MapView'; export default ( <Route path='/' component={Main}> <Route path='sale' component={Sale} /> <Route path='sale/:saleId' component={Sale} /> <IndexRoute component={SaleMap}/> </Route> );
src/components/home_screen/settings.js
shoumma/Mister-Poster
/** * the settings tab */ import React, { Component } from 'react' import { Text, View, TouchableOpacity, Alert, StyleSheet } from 'react-native' import { firebaseApp } from '../../firebase' import Icon from 'react-native-vector-icons/Ionicons' export default class Settings extends Component { constructor(props) { super(props) this.state = { user: '', email: '', signOutMsg: 'Sign Out' } } componentDidMount() { const user = firebaseApp.auth().currentUser if (user != null) { const name = user.displayName const uemail = user.email this.setState({ user: name, email: uemail, deleteErrMsg: '' }) } } render() { return ( <View> <TouchableOpacity style={styles.listItem} onPress={this._logOut.bind(this)}> <Icon name='md-log-out' size={30} color='rgba(0,0,0,.5)' style={styles.itemIcon}/> <Text style={styles.itemName}> {this.state.signOutMsg} - {this.state.user} </Text> </TouchableOpacity> <TouchableOpacity style={styles.listItem} onPress={this._deleteAccount.bind(this)}> <Icon name='md-close' size={30} color='rgba(0,0,0,.5)' style={styles.itemIcon}/> <Text style={[styles.itemName, { color: 'red' }]}> Delete my account </Text> </TouchableOpacity> <Text style={{flex: 1, margin: 20}}>{this.state.deleteErrMsg}</Text> </View> ) } _logOut() { this.props.onLogOut() } _deleteAccount() { Alert.alert( 'Delete Account!', 'Are you sure to delete your account?', [ {text: 'No', style: 'cancel'}, {text: 'Yes', onPress: () => this._deleteAccountConfirmed()}, ] ) } _deleteAccountConfirmed() { this.setState({ deleteErrMsg: '' }) if (firebaseApp.auth().currentUser) { firebaseApp.auth().currentUser.delete().then(() => { this.props.onLogOut() }).catch((error) => { this.setState({ deleteErrMsg: error.message }) }) } else { this.setState({ deleteErrMsg: 'Something went wrong!' }) } } } const styles = StyleSheet.create({ listItem: { marginTop: 10, height: 50, flexDirection: 'row', alignItems: 'center' }, itemIcon: { marginLeft: 20, marginRight: 20 }, itemName: { fontFamily: 'Roboto-Regular' } })
src/interface/report/Results/Overview/index.js
fyruna/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { hasPremium } from 'interface/selectors/user'; import Ad from 'interface/common/Ad'; import Checklist from './Checklist'; import Suggestions from './Suggestions'; class Overview extends React.PureComponent { static propTypes = { checklist: PropTypes.node, issues: PropTypes.array, premium: PropTypes.bool, }; render() { const { checklist, issues, premium } = this.props; return ( <div className="container"> <Checklist> {checklist} </Checklist> {premium === false && ( <div style={{ margin: '40px 0' }}> <Ad /> </div> )} <Suggestions style={{ marginBottom: 0 }}> {issues} </Suggestions> </div> ); } } const mapStateToProps = state => ({ premium: hasPremium(state), }); export default connect(mapStateToProps)(Overview);
tests/baselines/reference/tsxStatelessFunctionComponentOverload6.js
jwbay/TypeScript
//// [file.tsx] import React = require('react') export interface ClickableProps { children?: string; className?: string; } export interface ButtonProps extends ClickableProps { onClick: React.MouseEventHandler<any>; } export interface LinkProps extends ClickableProps { to: string; } export interface HyphenProps extends ClickableProps { "data-format": string; } let obj = { children: "hi", to: "boo" } let obj1: any; let obj2 = { onClick: () => {} } export function MainButton(buttonProps: ButtonProps): JSX.Element; export function MainButton(linkProps: LinkProps): JSX.Element; export function MainButton(hyphenProps: HyphenProps): JSX.Element; export function MainButton(props: ButtonProps | LinkProps | HyphenProps): JSX.Element { const linkProps = props as LinkProps; if(linkProps.to) { return this._buildMainLink(props); } return this._buildMainButton(props); } // OK const b0 = <MainButton to='/some/path'>GO</MainButton>; const b1 = <MainButton onClick={(e) => {}}>Hello world</MainButton>; const b2 = <MainButton {...obj} />; const b3 = <MainButton {...{to: 10000}} {...obj} />; const b4 = <MainButton {...obj1} />; // any; just pick the first overload const b5 = <MainButton {...obj1} to="/to/somewhere" />; // should pick the second overload const b6 = <MainButton {...obj2} />; const b7 = <MainButton {...{onClick: () => { console.log("hi") }}} />; const b8 = <MainButton {...{onClick() {}}} />; // OK; method declaration get retained (See GitHub #13365) const b9 = <MainButton to='/some/path' extra-prop>GO</MainButton>; const b10 = <MainButton to='/some/path' children="hi" >GO</MainButton>; const b11 = <MainButton onClick={(e) => {}} className="hello" data-format>Hello world</MainButton>; const b12 = <MainButton data-format="Hello world" /> //// [file.jsx] define(["require", "exports", "react"], function (require, exports, React) { "use strict"; exports.__esModule = true; var obj = { children: "hi", to: "boo" }; var obj1; var obj2 = { onClick: function () { } }; function MainButton(props) { var linkProps = props; if (linkProps.to) { return this._buildMainLink(props); } return this._buildMainButton(props); } exports.MainButton = MainButton; // OK var b0 = <MainButton to='/some/path'>GO</MainButton>; var b1 = <MainButton onClick={function (e) { }}>Hello world</MainButton>; var b2 = <MainButton {...obj}/>; var b3 = <MainButton {...{ to: 10000 }} {...obj}/>; var b4 = <MainButton {...obj1}/>; // any; just pick the first overload var b5 = <MainButton {...obj1} to="/to/somewhere"/>; // should pick the second overload var b6 = <MainButton {...obj2}/>; var b7 = <MainButton {...{ onClick: function () { console.log("hi"); } }}/>; var b8 = <MainButton {...{ onClick: function () { } }}/>; // OK; method declaration get retained (See GitHub #13365) var b9 = <MainButton to='/some/path' extra-prop>GO</MainButton>; var b10 = <MainButton to='/some/path' children="hi">GO</MainButton>; var b11 = <MainButton onClick={function (e) { }} className="hello" data-format>Hello world</MainButton>; var b12 = <MainButton data-format="Hello world"/>; });
ajax/libs/react-native-web/0.0.0-d48f63060/cjs/vendor/react-native/Animated/NativeAnimatedHelper.js
cdnjs/cdnjs
"use strict"; exports.__esModule = true; exports.generateNewAnimationId = generateNewAnimationId; exports.shouldUseNativeDriver = shouldUseNativeDriver; exports.default = void 0; var _NativeAnimatedModule = _interopRequireDefault(require("./NativeAnimatedModule")); var _NativeAnimatedTurboModule = _interopRequireDefault(require("./NativeAnimatedTurboModule")); var _NativeEventEmitter = _interopRequireDefault(require("../NativeEventEmitter")); var _Platform = _interopRequireDefault(require("../../../exports/Platform")); var _invariant = _interopRequireDefault(require("fbjs/lib/invariant")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * 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. * * * @format */ // TODO T69437152 @petetheheat - Delete this fork when Fabric ships to 100%. var NativeAnimatedModule = _Platform.default.OS === 'ios' && global.RN$Bridgeless ? _NativeAnimatedTurboModule.default : _NativeAnimatedModule.default; var __nativeAnimatedNodeTagCount = 1; /* used for animated nodes */ var __nativeAnimationIdCount = 1; /* used for started animations */ var nativeEventEmitter; var waitingForQueuedOperations = new Set(); var queueOperations = false; var queue = []; /** * Simple wrappers around NativeAnimatedModule to provide flow and autocomplete support for * the native module methods */ var API = { getValue: function getValue(tag, saveValueCallback) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); if (NativeAnimatedModule.getValue) { NativeAnimatedModule.getValue(tag, saveValueCallback); } }, setWaitingForIdentifier: function setWaitingForIdentifier(id) { waitingForQueuedOperations.add(id); queueOperations = true; }, unsetWaitingForIdentifier: function unsetWaitingForIdentifier(id) { waitingForQueuedOperations.delete(id); if (waitingForQueuedOperations.size === 0) { queueOperations = false; API.disableQueue(); } }, disableQueue: function disableQueue() { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); if (_Platform.default.OS === 'android') { NativeAnimatedModule.startOperationBatch(); } for (var q = 0, l = queue.length; q < l; q++) { queue[q](); } queue.length = 0; if (_Platform.default.OS === 'android') { NativeAnimatedModule.finishOperationBatch(); } }, queueOperation: function queueOperation(fn) { if (queueOperations) { queue.push(fn); } else { fn(); } }, createAnimatedNode: function createAnimatedNode(tag, config) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.createAnimatedNode(tag, config); }); }, startListeningToAnimatedNodeValue: function startListeningToAnimatedNodeValue(tag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.startListeningToAnimatedNodeValue(tag); }); }, stopListeningToAnimatedNodeValue: function stopListeningToAnimatedNodeValue(tag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.stopListeningToAnimatedNodeValue(tag); }); }, connectAnimatedNodes: function connectAnimatedNodes(parentTag, childTag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.connectAnimatedNodes(parentTag, childTag); }); }, disconnectAnimatedNodes: function disconnectAnimatedNodes(parentTag, childTag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.disconnectAnimatedNodes(parentTag, childTag); }); }, startAnimatingNode: function startAnimatingNode(animationId, nodeTag, config, endCallback) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.startAnimatingNode(animationId, nodeTag, config, endCallback); }); }, stopAnimation: function stopAnimation(animationId) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.stopAnimation(animationId); }); }, setAnimatedNodeValue: function setAnimatedNodeValue(nodeTag, value) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.setAnimatedNodeValue(nodeTag, value); }); }, setAnimatedNodeOffset: function setAnimatedNodeOffset(nodeTag, offset) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.setAnimatedNodeOffset(nodeTag, offset); }); }, flattenAnimatedNodeOffset: function flattenAnimatedNodeOffset(nodeTag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.flattenAnimatedNodeOffset(nodeTag); }); }, extractAnimatedNodeOffset: function extractAnimatedNodeOffset(nodeTag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.extractAnimatedNodeOffset(nodeTag); }); }, connectAnimatedNodeToView: function connectAnimatedNodeToView(nodeTag, viewTag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.connectAnimatedNodeToView(nodeTag, viewTag); }); }, disconnectAnimatedNodeFromView: function disconnectAnimatedNodeFromView(nodeTag, viewTag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.disconnectAnimatedNodeFromView(nodeTag, viewTag); }); }, restoreDefaultValues: function restoreDefaultValues(nodeTag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); // Backwards compat with older native runtimes, can be removed later. if (NativeAnimatedModule.restoreDefaultValues != null) { API.queueOperation(function () { return NativeAnimatedModule.restoreDefaultValues(nodeTag); }); } }, dropAnimatedNode: function dropAnimatedNode(tag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.dropAnimatedNode(tag); }); }, addAnimatedEventToView: function addAnimatedEventToView(viewTag, eventName, eventMapping) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.addAnimatedEventToView(viewTag, eventName, eventMapping); }); }, removeAnimatedEventFromView: function removeAnimatedEventFromView(viewTag, eventName, animatedNodeTag) { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); API.queueOperation(function () { return NativeAnimatedModule.removeAnimatedEventFromView(viewTag, eventName, animatedNodeTag); }); } }; /** * Styles allowed by the native animated implementation. * * In general native animated implementation should support any numeric property that doesn't need * to be updated through the shadow view hierarchy (all non-layout properties). */ var SUPPORTED_STYLES = { opacity: true, transform: true, borderRadius: true, borderBottomEndRadius: true, borderBottomLeftRadius: true, borderBottomRightRadius: true, borderBottomStartRadius: true, borderTopEndRadius: true, borderTopLeftRadius: true, borderTopRightRadius: true, borderTopStartRadius: true, elevation: true, zIndex: true, /* ios styles */ shadowOpacity: true, shadowRadius: true, /* legacy android transform properties */ scaleX: true, scaleY: true, translateX: true, translateY: true }; var SUPPORTED_TRANSFORMS = { translateX: true, translateY: true, scale: true, scaleX: true, scaleY: true, rotate: true, rotateX: true, rotateY: true, rotateZ: true, perspective: true }; var SUPPORTED_INTERPOLATION_PARAMS = { inputRange: true, outputRange: true, extrapolate: true, extrapolateRight: true, extrapolateLeft: true }; function addWhitelistedStyleProp(prop) { SUPPORTED_STYLES[prop] = true; } function addWhitelistedTransformProp(prop) { SUPPORTED_TRANSFORMS[prop] = true; } function addWhitelistedInterpolationParam(param) { SUPPORTED_INTERPOLATION_PARAMS[param] = true; } function validateTransform(configs) { configs.forEach(function (config) { if (!SUPPORTED_TRANSFORMS.hasOwnProperty(config.property)) { throw new Error("Property '" + config.property + "' is not supported by native animated module"); } }); } function validateStyles(styles) { for (var _key in styles) { if (!SUPPORTED_STYLES.hasOwnProperty(_key)) { throw new Error("Style property '" + _key + "' is not supported by native animated module"); } } } function validateInterpolation(config) { for (var _key2 in config) { if (!SUPPORTED_INTERPOLATION_PARAMS.hasOwnProperty(_key2)) { throw new Error("Interpolation property '" + _key2 + "' is not supported by native animated module"); } } } function generateNewNodeTag() { return __nativeAnimatedNodeTagCount++; } function generateNewAnimationId() { return __nativeAnimationIdCount++; } function assertNativeAnimatedModule() { (0, _invariant.default)(NativeAnimatedModule, 'Native animated module is not available'); } var _warnedMissingNativeAnimated = false; function shouldUseNativeDriver(config) { if (config.useNativeDriver == null) { console.warn('Animated: `useNativeDriver` was not specified. This is a required ' + 'option and must be explicitly set to `true` or `false`'); } if (config.useNativeDriver === true && !NativeAnimatedModule) { if (!_warnedMissingNativeAnimated) { console.warn('Animated: `useNativeDriver` is not supported because the native ' + 'animated module is missing. Falling back to JS-based animation. To ' + 'resolve this, add `RCTAnimation` module to this app, or remove ' + '`useNativeDriver`. ' + 'Make sure to run `pod install` first. Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md'); _warnedMissingNativeAnimated = true; } return false; } return config.useNativeDriver || false; } function transformDataType(value) { // Change the string type to number type so we can reuse the same logic in // iOS and Android platform if (typeof value !== 'string') { return value; } if (/deg$/.test(value)) { var degrees = parseFloat(value) || 0; var radians = degrees * Math.PI / 180.0; return radians; } else { return value; } } var _default = { API: API, addWhitelistedStyleProp: addWhitelistedStyleProp, addWhitelistedTransformProp: addWhitelistedTransformProp, addWhitelistedInterpolationParam: addWhitelistedInterpolationParam, validateStyles: validateStyles, validateTransform: validateTransform, validateInterpolation: validateInterpolation, generateNewNodeTag: generateNewNodeTag, generateNewAnimationId: generateNewAnimationId, assertNativeAnimatedModule: assertNativeAnimatedModule, shouldUseNativeDriver: shouldUseNativeDriver, transformDataType: transformDataType, // $FlowExpectedError - unsafe getter lint suppresion get nativeEventEmitter() { if (!nativeEventEmitter) { nativeEventEmitter = new _NativeEventEmitter.default(NativeAnimatedModule); } return nativeEventEmitter; } }; exports.default = _default;
test/integration/image-component/default/pages/priority.js
flybayer/next.js
import React from 'react' import Image from 'next/image' const Page = () => { return ( <div> <p>Priority Page</p> <Image priority id="basic-image" src="/test.jpg" width="400" height="400" ></Image> <Image loading="eager" id="basic-image" src="/test.png" width="400" height="400" ></Image> <Image priority id="responsive1" src="/wide.png" width="1200" height="700" layout="responsive" /> <Image priority id="responsive2" src="/wide.png" width="1200" height="700" layout="responsive" /> <p id="stubtext">This is the priority page</p> </div> ) } export default Page
app/javascript/mastodon/features/ui/components/video_modal.js
tootsuite/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Video from 'mastodon/features/video'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Footer from 'mastodon/features/picture_in_picture/components/footer'; import { getAverageFromBlurhash } from 'mastodon/blurhash'; export default class VideoModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.map.isRequired, statusId: PropTypes.string, options: PropTypes.shape({ startTime: PropTypes.number, autoPlay: PropTypes.bool, defaultVolume: PropTypes.number, }), onClose: PropTypes.func.isRequired, onChangeBackgroundColor: PropTypes.func.isRequired, }; componentDidMount () { const { media, onChangeBackgroundColor } = this.props; const backgroundColor = getAverageFromBlurhash(media.get('blurhash')); if (backgroundColor) { onChangeBackgroundColor(backgroundColor); } } render () { const { media, statusId, onClose } = this.props; const options = this.props.options || {}; return ( <div className='modal-root__modal video-modal'> <div className='video-modal__container'> <Video preview={media.get('preview_url')} frameRate={media.getIn(['meta', 'original', 'frame_rate'])} blurhash={media.get('blurhash')} src={media.get('url')} currentTime={options.startTime} autoPlay={options.autoPlay} volume={options.defaultVolume} onCloseVideo={onClose} detailed alt={media.get('description')} /> </div> <div className='media-modal__overlay'> {statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />} </div> </div> ); } }
src/Popup.react.js
z-vr/react-popup
import React from 'react'; import PropTypes from 'prop-types'; import key from 'keymaster'; import PopupStore from './Store'; import Header from './Header.react'; import Footer from './Footer.react'; import Constants from './Constants'; const defaultKeyFilter = key.filter; const Store = new PopupStore(); const hasClass = (element, className) => { if (element.classList) { return !!className && element.classList.contains(className); } return (` ${element.className} `).indexOf(` ${className} `) > -1; }; const handleClose = () => { key.deleteScope('react-popup'); key.filter = defaultKeyFilter; Store.close(); }; const initialState = { id: null, title: null, buttons: null, content: null, visible: false, className: null, noOverlay: false, position: false, closeOnOutsideClick: true, footer: null, }; class Component extends React.Component { static displayName = 'Popup'; static addShowListener(callback) { Store.on(Constants.SHOW, callback); } static removeShowListener(callback) { Store.removeListener(Constants.SHOW, callback); } static addCloseListener(callback) { Store.on(Constants.CLOSE, callback); } static removeCloseListener(callback) { Store.removeListener(Constants.CLOSE, callback); } static register(data) { const id = Store.getId(); Store.popups[id] = Object.assign({}, initialState, data); return id; } static queue(id) { if (!Object.prototype.hasOwnProperty.call(Store.popups, id)) { return false; } /** Add popup to queue */ Store.queue.push(id); /** Dispatch queue */ Store.dispatch(); return id; } static create(data, bringToFront) { /** Register popup */ const id = this.register(data); /** Queue popup */ if (bringToFront === true) { const currentlyActive = Store.active; Store.active = null; this.queue(id); this.queue(currentlyActive); Store.dispatch(); } else { this.queue(id); } return id; } static alert(text, title, bringToFront) { const data = { title, content: text, buttons: { right: ['ok'], }, }; return this.create(data, bringToFront); } static close() { Store.close(); } static registerPlugin(name, callback) { Store.plugins[name] = callback.bind(this); } static plugins() { return Store.plugins; } static refreshPosition(position) { return Store.refreshPosition(position); } static clearQueue() { return Store.clearQueue(); } constructor(props) { super(props); initialState.closeOnOutsideClick = this.props.closeOnOutsideClick; this.state = initialState; this.bound = { onShow: this.onShow.bind(this), onClose: this.onClose.bind(this), onRefresh: this.onRefresh.bind(this), containerClick: this.containerClick.bind(this), handleButtonClick: this.handleButtonClick.bind(this), }; this.boxRef = null; this.defaultKeyBindings = { ok: this.props.defaultOkKey, cancel: this.props.defaultCancelKey, }; } componentDidMount() { Store.on(Constants.SHOW, this.bound.onShow); Store.on(Constants.CLOSE, this.bound.onClose); Store.on(Constants.REFRESH, this.bound.onRefresh); } componentDidUpdate() { if (this.boxRef && !this.props.skipFocus) { this.boxRef.focus(); } this.setPosition(this.state.position); } componentWillUnmount() { key.deleteScope('react-popup'); key.filter = defaultKeyFilter; } /** * Refresh popup position * @param position * @private */ onRefresh(position) { this.setPosition(position); } /** * On popup close * @private */ onClose() { key.deleteScope('react-popup'); key.filter = defaultKeyFilter; this.setState(initialState); } /** * On popup show * @private */ onShow(id) { key.deleteScope('react-popup'); key.filter = () => { return true }; const popup = Store.activePopup(); if (popup.buttons && !Object.prototype.hasOwnProperty.call(popup.buttons, 'left')) { popup.buttons.left = []; } if (popup.buttons && !Object.prototype.hasOwnProperty.call(popup.buttons, 'right')) { popup.buttons.right = []; } this.setState({ id, title: popup.title, content: popup.content, buttons: popup.buttons, visible: true, className: popup.className, noOverlay: popup.noOverlay, position: popup.position, closeOnOutsideClick: popup.closeOnOutsideClick, footer: popup.footer, }, () => { key.setScope('react-popup'); if (this.props.escToClose) { key('esc', 'react-popup', this.handleKeyEvent.bind(this, 'cancel', this.state.id)); } if (this.state.buttons) { if (this.state.buttons.left.length) { this.state.buttons.left.forEach(button => this.bindKeyEvents(button)); } if (this.state.buttons.right.length) { this.state.buttons.right.forEach(button => this.bindKeyEvents(button)); } } }); } setPosition(position) { const box = this.boxRef; let boxPosition = position; if (!box) { return; } if (!boxPosition) { boxPosition = this.state.position; } if (!boxPosition) { box.style.opacity = 1; box.style.top = null; box.style.left = null; box.style.margin = null; return; } if (typeof boxPosition === 'function') { boxPosition.call(null, box); return; } console.log(boxPosition); box.style.top = `${parseInt(boxPosition.y, 10)}px`; box.style.left = `${parseInt(boxPosition.x, 10)}px`; box.style.margin = 0; box.style.opacity = 1; } /** * Handle container click * @param e * @private */ containerClick(e) { if (this.state.closeOnOutsideClick) { handleClose(); } } bindKeyEvents(button) { let code = null; if (typeof button === 'string') { code = this.defaultKeyBindings[button]; } else if (Object.prototype.hasOwnProperty.call(button, 'key')) { code = button.key; } if (this.props.escToClose && code === 'esc') { return; } if (code) { key(code, 'react-popup', this.handleKeyEvent.bind(this, button, this.state.id)); } } handleKeyEvent(button, id, e) { const excludeTags = ['INPUT', 'TEXTAREA', 'BUTTON']; if (this.state.id !== id || (button.key === 'enter' && excludeTags.indexOf(e.target.tagName) >= 0)) { return true; } if (typeof button === 'string') { handleClose(); } else if (Object.prototype.hasOwnProperty.call(button, 'action')) { this.handleButtonClick(button.action); } return false; } /** * Handle button clicks * @param action * @returns {*} * @private */ handleButtonClick(action) { if (typeof action === 'function') { return action.call(this, Store); } return null; } className(className) { return `${this.props.className}__${className}`; } wildClass(className, base) { if (!className) { return null; } if (this.props.wildClasses) { return className; } const finalClass = []; const classNames = className.split(' '); classNames.forEach((singleClass) => { finalClass.push(`${base}--${singleClass}`); }); return finalClass.join(' '); } render() { let { className } = this.props; let box = null; const overlayStyle = {}; if (this.state.visible) { let closeBtn = null; className += ` ${this.props.className}--visible`; if (this.props.closeBtn) { closeBtn = <button onClick={handleClose} className={`${this.props.className}__close`}>{this.props.closeHtml}</button>; } let boxClass = this.className('box'); if (this.state.className) { boxClass += ` ${this.wildClass(this.state.className, boxClass)}`; } box = ( <article role="dialog" tabIndex="-1" ref={(el) => { this.boxRef = el; }} style={{ opacity: 0, outline: 'none' }} className={boxClass}> {closeBtn} <Header title={this.state.title} className={this.className('box__header')} /> <div className={this.className('box__body')}> {this.state.content} </div> <Footer className={this.className('box__footer')} wildClasses={this.props.wildClasses} btnClass={this.props.btnClass} buttonClick={this.bound.handleButtonClick} onClose={handleClose} onOk={handleClose} defaultOk={this.props.defaultOk} defaultCancel={this.props.defaultCancel} buttons={this.state.buttons} footer={this.state.footer} /> </article> ); } if (this.state.noOverlay) { overlayStyle.background = 'transparent'; } return ( <div className={className}> <div role="presentation" onClick={this.bound.containerClick} className={this.className('overlay')} style={overlayStyle} /> {box} </div> ); } } Component.propTypes = { className: PropTypes.string, btnClass: PropTypes.string, closeBtn: PropTypes.bool, closeHtml: PropTypes.node, defaultOk: PropTypes.string, defaultOkKey: PropTypes.string, defaultCancel: PropTypes.string, defaultCancelKey: PropTypes.string, wildClasses: PropTypes.bool, closeOnOutsideClick: PropTypes.bool, escToClose: PropTypes.bool, skipFocus: PropTypes.bool, }; Component.defaultProps = { className: 'mm-popup', btnClass: 'mm-popup__btn', closeBtn: true, closeHtml: null, defaultOk: 'Ok', defaultOkKey: 'enter', defaultCancel: 'Cancel', defaultCancelKey: 'esc', wildClasses: false, closeOnOutsideClick: true, escToClose: true, skipFocus: false, }; export default Component;
app/components/ChargesModal/index.js
seanng/web-server
/** * * ChargesModal * */ import React from 'react'; import { Modal, Form, FormControl } from 'react-bootstrap'; import Button from '../Button'; import ChargesList from '../ChargesList'; import styled from 'styled-components'; import { FormattedMessage, injectIntl } from 'react-intl'; import messages from './messages'; class ChargesModal extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function header() { const H4 = styled.h4` font-size: 1.5em; ` return ( <Modal.Header closeButton> <H4> <FormattedMessage {...messages.header} values={{ name: this.props.stay.customerName, date: this.props.stay.checkInTime }} />&nbsp; </H4> </Modal.Header> ) } addCharge(e) { let charge = { stayId: this.props.stay.id, service: document.getElementById('serviceInput').value, charge: (document.getElementById('priceInput').value*1).toFixed(2), status: 'Unsettled', updated: false, } this.props.addCharge(charge); document.getElementById('serviceInput').value = ''; document.getElementById('priceInput').value = ''; } saveCharges(e) { let newCharges = this.props.charges.filter(charge => charge.updated === false); let newTotal = newCharges.reduce((prev, current) => (prev*1 + current.charge*1).toFixed(2), this.props.stay.totalCharge*1) let stayId = this.props.stay.id; this.props.saveCharges(newCharges, newTotal, stayId); } body() { const Upper = styled.div` padding-bottom: 20px; border-bottom: 1px dotted silver; ` const UpperBody = ( <Upper> <div className="row"> <div className="col-sm-7"> <FormControl id="serviceInput" type="text" placeholder={ this.props.intl.formatMessage(messages.service) } /> </div> <div className="col-sm-3"> <FormControl type="number" id="priceInput" placeholder={ this.props.intl.formatMessage(messages.price, { currency: this.props.stay.currency }) } /> </div> <div className="col-sm-2"> <Button onClick={this.addCharge.bind(this)} wide> <FormattedMessage {...messages.add} /> </Button> </div> </div> </Upper> ) return ( <Modal.Body> { UpperBody } <ChargesList charges={this.props.charges} currency={this.props.stay.currency} /> </Modal.Body> ) } footer() { const ModalFooter = styled.div` padding: 15px; ` return ( <ModalFooter> <div className="row"> <div className="col-xs-6"> <Button onClick={this.props.hide.bind(this)} wide> <FormattedMessage {...messages.cancel} /> </Button> </div> <div className="col-xs-6"> <Button onClick={this.saveCharges.bind(this)} wide> <FormattedMessage {...messages.save} /> </Button> </div> </div> </ModalFooter> ) } render() { return ( <Modal show={this.props.show} onHide={this.props.hide.bind(this)} bsSize={'lg'} > { this.header() } { this.body() } { this.footer() } </Modal> ); } } ChargesModal.propTypes = { }; export default injectIntl(ChargesModal);
__tests__/share/lookup-input.js
haasDev/starter
import React from 'react'; import LookupInput from '../../src/share/lookup-input'; import {mount} from 'enzyme'; import snapshot from '../snapshot'; describe('LookupInput', () => { it('should render', () => { snapshot(<LookupInput img="search" />); }); it('should call onChange fn when text is updated with entered text', () => { const onChange = jest.fn(); const wrapper = mount(<LookupInput img="search" onChange={onChange} />); const input = wrapper.find('input'); input.simulate('change', {target: {value: 'foo'}}); expect(onChange) .toHaveBeenCalledWith( expect.objectContaining({target: {value: 'foo'}}) ); }); it('should call onClick fn when the icon is clicked', () => { const onClick = jest.fn(); const wrapper = mount(<LookupInput img="search" onSubmit={onClick} />); const icon = wrapper.find('.icon'); icon.simulate('click'); expect(onClick).toHaveBeenCalled(); }); it('should call onClick fn when enter key is pressed', () => { const onEnterPress = jest.fn(); const wrapper = mount(<LookupInput img="search" onSubmit={onEnterPress} />); const input = wrapper.find('input'); input.simulate('keyPress', {which: 13}); expect(onEnterPress).toHaveBeenCalled(); }); });
src/modules/ShortText.js
broucz/mvu-react-form
import React from 'react'; import FieldValidationMessage from '../components/FieldValidationMessage'; import {shortText as inputStyle} from '../style'; // -- Model const model = ''; // -- Update const UPDATE = 'UPDATE'; const VALIDATE = 'VALIDATE'; const update = ( {state = model} = {}, {type, value} = {}, { validate: { expression , message: {advice, error} = {} } = {} } = {} ) => { switch (type) { case UPDATE: case VALIDATE: return (expression.test(value)) ? {state: value, feedback: {advice}} : {state: value, feedback: {error}}; default: return {state, feedback: {advice}}; } }; // -- View const view = ({state, dispatch, feedback}) => <div> <input type="text" value={state} style={inputStyle()} onChange={({target: {value}}) => dispatch({ type: UPDATE, value })} onBlur={({target: {value}}) => dispatch({ type: VALIDATE, value })} /> <FieldValidationMessage feedback={feedback}/> </div>; export {update, view};
files/highstock/2.1.6/highstock.src.js
towerz/jsdelivr
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highstock JS v2.1.6 (2015-06-12) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ /*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /(msie|trident)/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () { return UNDEFINED; }, charts = [], chartCount = 0, PRODUCT = 'Highstock', VERSION = '2.1.6', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'], // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getTimezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMilliseconds, setSeconds, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; // The Highcharts namespace Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {}; Highcharts.seriesTypes = seriesTypes; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ var extend = Highcharts.extend = function (a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; }; /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return obj && typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem.setAttribute(prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem.setAttribute(key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ var pick = Highcharts.pick = function () { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== UNDEFINED && arg !== null) { return arg; } } }; /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () { return UNDEFINED; }; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Return a length based on either the integer value, or a percentage of a base. */ function relativeLength (value, base) { return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value); } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ var wrap = Highcharts.wrap = function (obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; }; function getTZOffset(timestamp) { return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - getTZOffset(timestamp)), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 'w': day, // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = Highcharts.numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) { var normalized, i, retInterval = interval; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { retInterval = multiples[i]; if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) { break; } } // multiply back to the correct magnitude retInterval *= magnitude; return retInterval; } /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error (code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } // else ... if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 28 * 24 * 3600000, year: 364 * 24 * 3600000 }; /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ Highcharts.numberFormat = function (number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = +number || 0, c = decimals === -1 ? mathMin((n.toString().split('.')[1] || '').length, 20) : // Preserve decimals. Not huge numbers (#3793). (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(n).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "")); }; /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Fx.step, base; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && $.Tween) { // jQuery 1.8 model obj = $.Tween.propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { var elem; // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // Don't run animations on textual properties like align (#1821) if (fx.prop === 'align') { return; } // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) this.addAnimSetter('d', function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // Interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }); /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i, len = arr.length; for (i = 0; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (this[0]) { if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } } return ret; }; }, /** * Add an animation setter for a specific property */ addAnimSetter: function (prop, setter) { // jQuery 1.8 style if ($.Tween) { $.Tween.propHooks[prop] = { set: setter }; // pre 1.8 } else { $.fx.step[prop] = setter; } }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; delete eventArguments.returnValue; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161) } el.hasAnim = 1; // #3342 $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy $(el).stop(); } } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = Highcharts.each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', 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'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ' ' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/stock/2.1.6/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/stock/2.1.6/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: { align: 'center', // defer: true, // enabled: false, formatter: function () { return this.y === null ? '' : Highcharts.numberFormat(this.y, -1); }, style: { color: 'contrast', fontSize: '11px', fontWeight: 'bold', textShadow: '0 0 6px contrast, 0 0 3px contrast' }, verticalAlign: 'bottom', // above singular point x: 0, y: 0, // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, padding: 5 // shadow: false }, cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, footerFormat: '', //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var globalOptions = defaultOptions.global, useUTC = globalOptions.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; Date = globalOptions.Date || window.Date; timezoneOffset = useUTC && globalOptions.timezoneOffset; getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset; makeTime = function (year, month, date, hours, minutes, seconds) { var d; if (useUTC) { d = Date.UTC.apply(0, arguments); d += getTZOffset(d); } else { d = new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); } return d; }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMilliseconds = SET + 'Milliseconds'; setSeconds = SET + 'Seconds'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/, hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = rgbaRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = hexRegEx.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = rgbRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity, raw: input }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions, {}); //#2625 if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')'); } }, /** * Apply a polyfill to the text-stroke CSS property, by copying the text element * and apply strokes to the copy. * * docs: update default, document the polyfill and the limitations on hex colors and pixel values, document contrast pseudo-color * TODO: * - update defaults */ applyTextShadow: function (textShadow) { var elem = this.element, tspans, hasContrast = textShadow.indexOf('contrast') !== -1, styles = {}, // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check // this again with new IE release. In exports, the rendering is passed to PhantomJS. supports = this.renderer.forExport || (elem.style.textShadow !== UNDEFINED && !isIE); // When the text shadow is set to contrast, use dark stroke for light text and vice versa if (hasContrast) { styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill)); } // Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this, // it removes the text shadows. if (isWebKit) { styles.textRendering = 'geometricPrecision'; } /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/) if (elem.textContent.indexOf('2.') === 0) { elem.style['text-shadow'] = 'none'; supports = false; } // */ // No reason to polyfill, we've got native support if (supports) { css(elem, styles); // Apply altered textShadow or textRendering workaround } else { this.fakeTS = true; // Fake text shadow // In order to get the right y position of the clones, // copy over the y setter this.ySetter = this.xSetter; tspans = [].slice.call(elem.getElementsByTagName('tspan')); each(textShadow.split(/\s?,\s?/g), function (textShadow) { var firstChild = elem.firstChild, color, strokeWidth; textShadow = textShadow.split(' '); color = textShadow[textShadow.length - 1]; // Approximately tune the settings to the text-shadow behaviour strokeWidth = textShadow[textShadow.length - 2]; if (strokeWidth) { each(tspans, function (tspan, y) { var clone; // Let the first line start at the correct X position if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); y = elem.getAttribute('y'); tspan.setAttribute('y', y || 0); if (y === null) { elem.setAttribute('y', 0); } } // Create the clone and apply shadow properties clone = tspan.cloneNode(1); attr(clone, { 'class': PREFIX + 'text-shadow', 'fill': color, 'stroke': color, 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3), 'stroke-width': strokeWidth, 'stroke-linejoin': 'round' }); elem.insertBefore(clone, firstChild); }); } }); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element); } // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } return ret; }, updateShadows: function (key, value) { var shadows = this.shadows, i = shadows.length; while (i--) { shadows[i].setAttribute( key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) || elemWrapper.textWidth; // #3501 // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { css(elemWrapper.element, styles); } else { /*jslint unparam: true*/ hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); // Delete bBox memo when the rotation changes //delete wrapper.bBox; } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function (reload) { var wrapper = this, bBox,// = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad, textStr = wrapper.textStr, textShadow, elemStyle = element.style, toggleTextShadowShim, cacheKey; if (textStr !== UNDEFINED) { // Properties that affect bounding box cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(','); // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num:' + textStr.toString().length + cacheKey; // Caching all strings reduces rendering time by 4-5%. } else { cacheKey = textStr + cacheKey; } } if (cacheKey && !reload) { bBox = renderer.cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. // When the text shadow shim is used, we need to hide the fake shadows // to get the correct bounding box (#3872) toggleTextShadowShim = this.fakeTS && function (display) { each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) { tspan.style.display = display; }); }; // Workaround for #3842, Firefox reporting wrong bounding box for shadows if (isFirefox && elemStyle.textShadow) { textShadow = elemStyle.textShadow; elemStyle.textShadow = ''; } else if (toggleTextShadowShim) { toggleTextShadowShim(NONE); } bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; // #3842 if (textShadow) { elemStyle.textShadow = textShadow; } else if (toggleTextShadowShim) { toggleTextShadowShim(''); } } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it renderer.cache[cacheKey] = bBox; } return bBox; }, /** * Show the element */ show: function (inherit) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881) if (inherit && this.element.namespaceURI === SVG_NS) { this.element.removeAttribute('visibility'); } else { this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); } return this; }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, element = this.element, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // Mark as added this.added = true; // If we're adding to renderer root, or other elements in the group // have a z index, we need to handle it if (!parent || parent.handleZ || this.zIndex) { inserted = this.zIndexSetter(); } // If zIndex is not handled, append at the end if (!inserted) { (parent ? parent.element : renderer.box).appendChild(element); } // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * this['stroke-width']; } value = value.join(',') .replace('NaN', 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.textContent = (String(pick(value), '')).replace(/<[^>]*>/g, ''); // #3276 #3895 }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, zIndexSetter: function (value, key) { var renderer = this.renderer, parentGroup = this.parentGroup, parentWrapper = parentGroup || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, otherElement, otherZIndex, element = this.element, inserted, run = this.added, i; if (defined(value)) { element.setAttribute(key, value); // So we can read it for other elements in the group value = +value; if (this[key] === value) { // Only update when needed (#3865) run = false; } this[key] = value; } // Insert according to this and other elements' zIndex. Before .add() is called, // nothing is done. Then on add, or by later calls to zIndexSetter, the node // is placed on the right place in the DOM. if (run) { value = this.zIndex; if (value && parentGroup) { parentGroup.handleZ = true; } childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length && !inserted; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // Insert before the first element with a higher zIndex pInt(otherZIndex) > value || // If no zIndex given, insert before the first element with a zIndex (!defined(value) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; } } if (!inserted) { parentNode.appendChild(element); } } return inserted; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { return (this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style)); }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textShadow = textStyles && textStyles.textShadow, ellipsis = textStyles && textStyles.textOverflow === 'ellipsis', i = childNodes.length, tempParent = width && !wrapper.added && this.box, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }, unescapeAngleBrackets = function (inputStr) { return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr))); return; // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (tempParent) { tempParent.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' '); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } /*if (width) { renderer.breakText(wrapper, width); }*/ // Check width and apply soft breaks or ellipsis if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'), tooLong, wasTooLong, actualWidth, rest = [], dy = getLineHeight(tspan), softLineNo = 1, rotation = wrapper.rotation, wordStr = span, // for ellipsis cursor = wordStr.length, // binary search cursor bBox; while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) { wrapper.rotation = 0; // discard rotation when computing box bBox = wrapper.getBBox(true); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; // For ellipsis, do a binary search for the correct string length if (wasTooLong === undefined) { wasTooLong = tooLong; // First time } if (ellipsis && wasTooLong) { cursor /= 2; if (wordStr === '' || (!tooLong && cursor < 0.5)) { words = []; // All ok, break out } else { if (tooLong) { wasTooLong = true; } wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor)); words = [wordStr + (width > 3 ? '\u2026' : '')]; tspan.removeChild(tspan.firstChild); } // Looping down, this is the first word sequence that is not too long, // so we can move on to build the next line. } else if (!tooLong || words.length === 1) { words = rest; rest = []; if (words.length) { softLineNo++; tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } if (wasTooLong) { wrapper.attr('title', wrapper.textStr); } wrapper.rotation = rotation; } spanNo++; } } }); }); if (tempParent) { tempParent.removeChild(textNode); // attach it to the DOM to read offset width } // Apply the text shadow if (textShadow && wrapper.applyTextShadow) { wrapper.applyTextShadow(textShadow); } } }, /* breakText: function (wrapper, width) { var bBox = wrapper.getBBox(), node = wrapper.element, textLength = node.textContent.length, pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width increment = 0, finalPos; if (bBox.width > width) { while (finalPos === undefined) { textLength = node.getSubStringLength(0, pos); if (textLength <= width) { if (increment === -1) { finalPos = pos; } else { increment = 1; } } else { if (increment === 1) { finalPos = pos - 1; } else { increment = -1; } } pos += increment; } } console.log(finalPos, node.getSubStringLength(0, finalPos)) }, */ /** * Returns white for dark colors and black for bright colors */ getContrast: function (color) { color = Color(color).rgba; return color[0] + color[1] + color[2] > 384 ? '#000000' : '#FFFFFF'; }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function () { if (curState !== 3) { callback.call(label); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); wrapper.xSetter = function (value) { this.element.setAttribute('cx', value); }; wrapper.ySetter = function (value) { this.element.setAttribute('cy', value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value) { attr(this.element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]); // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; wrapper.count = 0; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { fontSize = fontSize || this.style.fontSize; if (elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement fontSize = win.getComputedStyle(elem, "").fontSize; } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Correct X and Y positioning of a label for rotation (#1764) */ rotCorr: function (baseline, rotation, alterY) { var y = baseline; if (rotation && alterY) { y = mathMax(y * mathCos(rotation * deg2rad), 4); } return { x: (-baseline / 3) * mathSin(rotation * deg2rad), y: y }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) && text.getBBox(); //#3295 && 3514 box failure when string equals 0 wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding) + crispAdjust; boxY = (baseline ? -baselineOffset : 0) + crispAdjust; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.attr('fill', NONE).add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = wrapper.padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, mathRound(value) - crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } if (styles && styles.textOverflow === 'ellipsis') { styles.whiteSpace = 'nowrap'; styles.overflow = 'hidden'; } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element; // faking getBBox in exported SVG in legacy IE // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows, styles = wrapper.styles; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } width = pick(wrapper.elemWidth, elem.offsetWidth); // Update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: (styles && styles.whiteSpace) || 'normal' // #3331 }); width = textWidth; } wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; }; // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Keep the whiteSpace style outside the wrapper.styles collection element.style.whiteSpace = 'nowrap'; // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, visibilitySetter: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: RELATIVE})); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.cache = {}; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], count: 0, left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; // first call if (!defined(label)) { tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) //.attr(attr) // without position absolute, IE export sometimes is wrong .css(merge(labelOptions.style)) .add(axis.labelGroup) : null; tick.labelLength = label && label.getBBox().width; // Un-rotated length tick.rotation = 0; // Base value to detect change for new calls to getBBox // update } else if (label) { label.attr({ text: str }); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { return this.label ? this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] : 0; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (xy) { var axis = this.axis, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, spacing[3]), rightBound = pick(axis.labelRight, chartWidth - spacing[1]), label = this.label, rotation = this.rotation, factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign], labelWidth = label.getBBox().width, slotWidth = axis.slotWidth, xCorrection = factor, goRight = 1, leftPos, rightPos, textWidth; // Check if the label overshoots the chart spacing box. If it does, move it. // If it now overshoots the slotWidth, add ellipsis. if (!rotation) { leftPos = pxPos - factor * labelWidth; rightPos = pxPos + (1 - factor) * labelWidth; if (leftPos < leftBound) { slotWidth = xy.x + slotWidth * (1 - factor) - leftBound; } else if (rightPos > rightBound) { slotWidth = rightBound - xy.x + slotWidth * factor; goRight = -1; } slotWidth = mathMin(axis.slotWidth, slotWidth); // #4177 if (slotWidth < axis.slotWidth && axis.labelAlign === 'center') { xy.x += goRight * (axis.slotWidth - slotWidth - xCorrection * (axis.slotWidth - mathMin(labelWidth, slotWidth))); } // If the label width exceeds the available space, set a text width to be // picked up below. Also, if a width has been set before, we need to set a new // one because the reported labelWidth will be limited by the box (#3938). if (labelWidth > slotWidth || (axis.autoRotation && label.styles.width)) { textWidth = slotWidth; } // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) { textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound); } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) { textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad)); } if (textWidth) { label.css({ width: textWidth, textOverflow: 'ellipsis' }); } }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = pick(labelOptions.y, rotCorr.y + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))), line; x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { line = (index / (step || 1) % staggerLines); y += line * (axis.labelOffset / staggerLines); } return { x: x, y: mathRound(y) }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = /*axis.labelStep || */labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { tick.handleOverflow(xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ Highcharts.PlotLineOrBand = function (axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; Highcharts.PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs = {}, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band path = axis.getPlotBandPath(from, to, options); if (color) { attribs.fill = color; } if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; if (label) { plotLine.label = label = label.destroy(); } } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation }; if (defined(zIndex)) { attribs.zIndex = zIndex; } plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .css(optionsLabel.style) .add(); } // get the bounding box and align the label // #3000 changed to better handle choice between plotband or plotline xs = [path[1], path[4], (isBand ? path[6] : path[1])]; ys = [path[2], path[5], (isBand ? path[7] : path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * Object with members for extending the Axis prototype */ AxisPlotLineOrBandExtension = { /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true); if (path && toPath && path.toString() !== toPath.toString()) { // #3836 path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, addPlotBand: function (options) { return this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { return this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new Highcharts.PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ var Axis = Highcharts.Axis = function () { this.init.apply(this, arguments); }; Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#D8D8D8', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: { enabled: true, // rotation: 0, // align: 'center', // step: null, style: { color: '#606060', cursor: 'default', fontSize: '11px' }, x: 0, y: 15 /*formatter: function () { return this.value; },*/ }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return Highcharts.numberFormat(this.total, -1); }, style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' }) } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { autoRotation: [-45], x: 0, y: null // based on font size // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for top axes */ defaultTopAxisOptions: { labels: { autoRotation: [-45], x: 0, y: -15 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = axis.names || []; // Preserve on update (#3830) // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = Highcharts.numberFormat(value, 0); } else { // small numbers ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.ignoreMinPadding = axis.ignoreMaxPadding = null; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this.linkedParent || this, // #1417 sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, doPostTranslate = (axis.doPostTranslate || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (doPostTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (doPostTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB, /** * Check if x is between a and b. If not, either move to a/b or skip, * depending on the force parameter. */ between = function (x, a, b) { if (x < a || x > b) { if (force) { x = mathMin(mathMax(a, x), b); } else { skip = true; } } return x; }; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; x1 = x2 = between(x1, axisLeft, axisLeft + axis.width); } else { x1 = axisLeft; x2 = cWidth - axis.right; y1 = y2 = between(y1, axisTop, axisTop + axis.height); } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, min = axis.min, max = axis.max, range = max - min, len; // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them. if (range && range / minorTickInterval < axis.len / 3) { // #3875 if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), min, max, options.startOfWeek ) ); } else { for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) { minorTickPositions.push(pos); } } } axis.trimTicks(minorTickPositions); // #3652 #3743 return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA, isXAxis = axis.isXAxis; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); if (!axis.single) { // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); } // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value if (isXAxis) { axis.closestPointRange = closestPointRange; } } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickInterval: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, categories = axis.categories; if (!isDatetimeAxis && !categories && !isLinked) { this.getTickAmount(); } // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) if (axis.pointRange) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange); if (!tickIntervalOption && axis.tickInterval < minTickInterval) { axis.tickInterval = minTickInterval; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog && !tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 0.5 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount ); } // Prevent ticks from getting so close that we can't draw the labels if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length axis.tickInterval = axis.unsquish(); } this.setTickPositions(); }, /** * Now we have computed the normalized tickInterval, get the tick positions */ setTickPositions: function () { var options = this.options, tickPositions, tickPositionsOption = options.tickPositions, tickPositioner = options.tickPositioner, startOnTick = options.startOnTick, endOnTick = options.endOnTick, single; // Set the tickmarkOffset this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' && this.tickInterval === 1) ? 0.5 : 0; // #3202 // get minorTickInterval this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ? this.tickInterval / 5 : options.minorTickInterval; // Find the tick positions this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565) if (!tickPositions) { if (this.isDatetimeAxis) { tickPositions = this.getTimeTicks( this.normalizeTimeTickInterval(this.tickInterval, options.units), this.min, this.max, options.startOfWeek, this.ordinalPositions, this.closestPointRange, true ); } else if (this.isLog) { tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max); } else { tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max); } this.tickPositions = tickPositions; // Run the tick positioner callback, that allows modifying auto tick positions. if (tickPositioner) { tickPositioner = tickPositioner.apply(this, [this.min, this.max]); if (tickPositioner) { this.tickPositions = tickPositions = tickPositioner; } } } if (!this.isLinked) { // reset min/max or remove extremes based on start/end on tick this.trimTicks(tickPositions, startOnTick, endOnTick); // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (this.min === this.max && defined(this.min) && !this.tickAmount) { // Substract half a unit (#2619, #2846, #2515, #3390) single = true; this.min -= 0.5; this.max += 0.5; } this.single = single; if (!tickPositionsOption && !tickPositioner) { this.adjustTickAmount(); } } }, /** * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max */ trimTicks: function (tickPositions, startOnTick, endOnTick) { var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = this.minPointOffset || 0; if (startOnTick) { this.min = roundedMin; } else if (this.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (endOnTick) { this.max = roundedMax; } else if (this.max + minPointOffset < roundedMax) { tickPositions.pop(); } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } }, /** * Set the max ticks of either the x and y axis collection */ getTickAmount: function () { var others = {}, // Whether there is another axis to pair with this one hasOther, options = this.options, tickAmount = options.tickAmount, tickPixelInterval = options.tickPixelInterval; if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial && !this.isLog && options.startOnTick && options.endOnTick) { tickAmount = 2; } if (!tickAmount && this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) { // Check if there are multiple axes in the same pane each(this.chart[this.coll], function (axis) { var options = axis.options, horiz = axis.horiz, key = [horiz ? options.left : options.top, horiz ? options.width : options.height, options.pane].join(','); if (others[key]) { if (axis.series.length) { hasOther = true; // #4201 } } else { others[key] = 1; } }); if (hasOther) { // Add 1 because 4 tick intervals require 5 ticks (including first and last) tickAmount = mathCeil(this.len / tickPixelInterval) + 1; } } // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This // prevents the axis from adding ticks that are too far away from the data extremes. if (tickAmount < 4) { this.finalTickAmt = tickAmount; tickAmount = 5; } this.tickAmount = tickAmount; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var tickInterval = this.tickInterval, tickPositions = this.tickPositions, tickAmount = this.tickAmount, finalTickAmt = this.finalTickAmt, currentTickAmount = tickPositions && tickPositions.length, i, len; if (currentTickAmount < tickAmount) { // TODO: Check #3411 while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + tickInterval )); } this.transA *= (currentTickAmount - 1) / (tickAmount - 1); this.max = tickPositions[tickPositions.length - 1]; // We have too many ticks, run second pass to try to reduce ticks } else if (currentTickAmount > tickAmount) { this.tickInterval *= 2; this.setTickPositions(); } // The finalTickAmt property is set in getTickAmount if (defined(finalTickAmt)) { i = len = tickPositions.length; while (i--) { if ( (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last ) { tickPositions.splice(i, 1); } } this.finalTickAmt = UNDEFINED; } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { // reset stacks if (!axis.isXAxis) { for (type in stacks) { for (i in stacks[type]) { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickInterval(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (!axis.isXAxis) { if (axis.oldStacks) { stacks = axis.stacks = axis.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true each(axis.series, function (serie) { delete serie.kdTree; }); // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options; // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) { newMin = UNDEFINED; } if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values if (percentRegex.test(height)) { height = parseFloat(height) / 100 * chart.plotHeight; } if (percentRegex.test(top)) { top = parseFloat(top) / 100 * chart.plotHeight + chart.plotTop; } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Prevent the ticks from getting so close we can't draw the labels. On a horizontal * axis, this is handled by rotating the labels, removing ticks and adding ellipsis. * On a vertical axis remove ticks and add ellipsis. */ unsquish: function () { var chart = this.chart, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, tickInterval = this.tickInterval, newTickInterval = tickInterval, slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval), rotation, rotationOption = labelOptions.rotation, labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), step, bestScore = Number.MAX_VALUE, autoRotation, // Return the multiple of tickInterval that is needed to avoid collision getStep = function (spaceNeeded) { var step = spaceNeeded / (slotSize || 1); step = step > 1 ? mathCeil(step) : 1; return step * tickInterval; }; if (horiz) { autoRotation = defined(rotationOption) ? [rotationOption] : slotSize < pick(labelOptions.autoRotationLimit, 80) && !labelOptions.staggerLines && !labelOptions.step && labelOptions.autoRotation; if (autoRotation) { // Loop over the given autoRotation options, and determine which gives the best score. The // best score is that with the lowest number of steps and a rotation closest to horizontal. each(autoRotation, function (rot) { var score; if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891 step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot))); score = step + mathAbs(rot / 360); if (score < bestScore) { bestScore = score; rotation = rot; newTickInterval = step; } } }); } } else { newTickInterval = getStep(labelMetrics.h); } this.autoRotation = autoRotation; this.labelRotation = rotation; return newTickInterval; }, renderUnsquish: function () { var chart = this.chart, renderer = chart.renderer, tickPositions = this.tickPositions, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, margin = chart.margin, slotCount = this.categories ? tickPositions.length : tickPositions.length - 1, slotWidth = this.slotWidth = (horiz && !labelOptions.step && !labelOptions.rotation && ((this.staggerLines || 1) * chart.plotWidth) / slotCount) || (!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931, innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))), attr = {}, labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), css, labelLength = 0, label, i, pos; // Set rotation option unless it is "auto", like in gauges if (!isString(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } // Handle auto rotation on horizontal axis if (this.autoRotation) { // Get the longest label length each(tickPositions, function (tick) { tick = ticks[tick]; if (tick && tick.labelLength > labelLength) { labelLength = tick.labelLength; } }); // Apply rotation only if the label is too wide for the slot, and // the label is wider than its height. if (labelLength > innerWidth && labelLength > labelMetrics.h) { attr.rotation = this.labelRotation; } else { this.labelRotation = 0; } // Handle word-wrap or ellipsis on vertical axis } else if (slotWidth) { // For word-wrap or ellipsis css = { width: innerWidth + PX, textOverflow: 'clip' }; // On vertical axis, only allow word wrap if there is room for more lines. i = tickPositions.length; while (!horiz && i--) { pos = tickPositions[i]; label = ticks[pos].label; if (label) { // Reset ellipsis in order to get the correct bounding box (#4070) if (label.styles.textOverflow === 'ellipsis') { label.css({ textOverflow: 'clip' }); } if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) { label.specCss = { textOverflow: 'ellipsis' }; } } } } // Add ellipsis if the label length is significantly longer than ideal if (attr.rotation) { css = { width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX, textOverflow: 'ellipsis' }; } // Set the explicit or automatic label alignment this.labelAlign = attr.align = labelOptions.align || this.autoLabelAlign(this.labelRotation); // Apply general and specific CSS each(tickPositions, function (pos) { var tick = ticks[pos], label = tick && tick.label; if (label) { if (css) { label.css(merge(css, label.specCss)); } delete label.specCss; label.attr(attr); tick.rotation = attr.rotation; } }); // TODO: Why not part of getLabelPosition? this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side === 2); }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n, lineHeightCorrection; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(); } if (hasData || axis.isLinked) { // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); axis.renderUnsquish(); each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0; labelOffsetPadded = labelOffset + titleMargin + (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection)); axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded // #3027 ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, xOption = axisTitleOptions.x || 0, yOption = axisTitleOptions.y || 0, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption, y: horiz ? offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, to; // Reset axis.labelEdge.length = 0; //axis.justifyToPlot = overflow === 'justify'; axis.overlap = false; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions, function (pos, i) { // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && (axis.min === 0 || axis.single)) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair */ drawCrosshair: function (e, point) { // docs: Missing docs for Axis.crosshair. Also for properties. var path, options = this.crosshair, animation = options.animation, pos, attribs, categorized; if ( // Disabled in options !this.crosshair || // Snap ((defined(point) || !pick(this.crosshair.snap, true)) === false) || // Not on this axis (#4095, #2888) (point && point.series && point.series[this.coll] !== this) ) { this.hideCrosshair(); } else { // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { /*jslint eqeq: true*/ pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834 /*jslint eqeq: false*/ } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189 } else { path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189 } if (path === null) { this.hideCrosshair(); return; } // Draw the cross if (this.cross) { this.cross .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation); } else { categorized = this.categories && !this.isRadial; attribs = { 'stroke-width': options.width || (categorized ? this.transA : 1), stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'), zIndex: options.zIndex || 2 }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min - getTZOffset(min)), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 minDate[setMilliseconds](interval >= timeUnits.second ? 0 : // #3935 count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654 if (interval >= timeUnits.second) { // second minDate[setSeconds](interval >= timeUnits.minute ? 0 : // #3935 count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits.minute) { // minute minDate[setMinutes](interval >= timeUnits.hour ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits.hour) { // hour minDate[setHours](interval >= timeUnits.day ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits.day) { // day minDate[setDate](interval >= timeUnits.month ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits.month) { // month minDate[setMonth](interval >= timeUnits.year ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits.year) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits.week) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; if (timezoneOffset || getTimezoneOffset) { minDate = minDate.getTime(); minDate = new Date(minDate + getTZOffset(minDate)); } minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), localTimezoneOffset = (timeUnits.day + (useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000) ) % timeUnits.day; // #950, #3359 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits.year) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits.month) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits.day || interval === timeUnits.week)) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits.day ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset; }), function (time) { higherRanks[time] = 'day'; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; }; /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) { var units = unitsOption || [[ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1, 2] ], [ 'week', [1, 2] ], [ 'month', [1, 2, 3, 4, 6] ], [ 'year', null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits.year && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval( tickInterval / interval, multiples, unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360 ); return { unitRange: interval, count: count, unitName: unit[0] }; };/** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -9999 }); // #2301, #2657 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.label.attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function (delay) { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(delay, this.options.hideDelay, 500)); } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotLeft = chart.plotLeft, plotX = 0, plotY = 0, yAxis, xAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; xAxis = point.series.xAxis; plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0); plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, h = point.h || 0, // #4117 swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft], // The far side is right or bottom preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = alignedLeft - h < 0 ? alignedLeft : alignedLeft - h; } else if (roomRight) { ret[dim] = alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h; } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { return false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), s; // build the header s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header // build the values s = s.concat(tooltip.bodyFormatter(items)); // footer s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow, h: anchor[2] || 0 }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y || 0), // can be undefined (#3977) point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Get the best X date format based on the closest point range on the axis. */ getXDateFormat: function (point, options, xAxis) { var xDateFormat, dateTimeLabelFormats = options.dateTimeLabelFormats, closestPointRange = xAxis && xAxis.closestPointRange, n, blank = '01-01 00:00:00.000', strpos = { millisecond: 15, second: 12, minute: 9, hour: 6, day: 3 }, date, lastN = 'millisecond'; // for sub-millisecond data, #4223 if (closestPointRange) { date = dateFormat('%m-%d %H:%M:%S.%L', point.x); for (n in timeUnits) { // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek && date.substr(6) === blank.substr(6)) { n = 'week'; break; // The first format that is too great for the range } else if (timeUnits[n] > closestPointRange) { n = lastN; break; // If the point is placed every day at 23:59, we need to show // the minutes as well. #2637. } else if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) { break; } // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition if (n !== 'week') { lastN = n; } } if (n) { xDateFormat = dateTimeLabelFormats[n]; } } else { xDateFormat = dateTimeLabelFormats.day; } return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 }, /** * Format the footer/header of the tooltip * #3397: abstraction to enable formatting of footer and header */ tooltipFooterHeaderFormatter: function (point, isFooter) { var footOrHead = isFooter ? 'footer' : 'header', series = point.series, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), formatString = tooltipOptions[footOrHead+'Format']; // Guess the best date format based on the closest point distance (#568, #3418) if (isDateTime && !xDateFormat) { xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis); } // Insert the footer date format if any if (isDateTime && xDateFormat) { formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(formatString, { point: point, series: series }); }, /** * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item, * abstracting this functionality allows to easily overwrite and extend it. */ bodyFormatter: function (items) { return map(items, function (item) { var tooltipOptions = item.series.tooltipOptions; return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat); }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = pick(options.tooltip.followTouchMove, true); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || window.event; // Framework specific normalizing (#1165) e = washMouseEvent(e); // More IE normalizing, needs to go after washMouseEvent if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, shared = tooltip ? tooltip.shared : false, followPointer, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, distance = chart.chartWidth, anchor, noSharedTooltip, directTouch, kdpoints = [], kdpoint, kdpointT; // For hovering over the empty parts of the plot area (hoverSeries is undefined). // If there is one series with point tracking (combo chart), don't go to nearest neighbour. if (!shared && !hoverSeries) { for (i = 0; i < series.length; i++) { if (series[i].directTouch || !series[i].options.stickyTracking) { series = []; } } } // If it has a hoverPoint and that series requires direct touch (like columns), // use the hoverPoint (#3899). Otherwise, search the k-d tree. if (!shared && hoverSeries && hoverSeries.directTouch && hoverPoint) { kdpoint = hoverPoint; // Handle shared tooltip or cases where a series is not yet hovered } else { // Find nearest points on all series each(series, function (s) { // Skip hidden series noSharedTooltip = s.noSharedTooltip && shared; directTouch = !shared && s.directTouch; if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821 kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828 if (kdpointT) { kdpoints.push(kdpointT); } } }); // Find absolute nearest point each(kdpoints, function (p) { if (p && typeof p.dist === 'number' && p.dist < distance) { distance = p.dist; kdpoint = p; } }); } // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200 if (kdpoint && (kdpoint !== this.prevKDPoint || (tooltip && tooltip.isHidden))) { // Draw tooltip if necessary if (shared && !kdpoint.series.noSharedTooltip) { i = kdpoints.length; while (i--) { if (kdpoints[i].clientX !== kdpoint.clientX || kdpoints[i].series.noSharedTooltip) { kdpoints.splice(i, 1); } } if (kdpoints.length && tooltip) { tooltip.refresh(kdpoints, e); } // do mouseover on all points except the closest each(kdpoints, function (point) { if (point !== kdpoint) { point.onMouseOver(e); } }); // #3919, #3985 do mouseover on the closest point last to ensure it is the hoverpoint ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoint).onMouseOver(e); } else { if (tooltip) { tooltip.refresh(kdpoint, e); } kdpoint.onMouseOver(e); } this.prevKDPoint = kdpoint; // Update positions (regardless of kdpoint or hoverPoint) } else { followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Crosshair each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(kdpoint, hoverPoint)); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, hoverPoints = chart.hoverPoints, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); each(chart.axes, function (axis) { if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) { axis.drawCrosshair(null, hoverPoint); } else { axis.hideCrosshair(); } }); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = chart.hoverPoints = chart.hoverPoint = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var pointer = this, chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569 var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes max: mathMax(selectionMin, selectionMax) }); runZoom = true; } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { var chart = charts[hoverChartIndex]; if (chart) { chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; hoverChartIndex = chart.index; e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement, relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499 if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && relatedSeries !== series) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); e.originalEvent = e; // #3913 if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // Don't initiate panning until the user has pinched. This prevents us from // blocking page scrolling as users scroll down a long page (#4210). if (touchesLength > 1) { self.initiated = true; } // On touch devices, only proceed to trigger click if a handler is defined if (hasZoom && self.initiated && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && self.followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, /** * General touch handler shared by touchstart and touchmove. */ touch: function (e, start) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) { // Run mouse events and display tooltip etc if (start) { this.runPointActions(e); } this.pinch(e); } else if (start) { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchStart: function (e) { this.touch(e, true); }, onContainerTouchMove: function (e) { this.touch(e); }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, callback) { var p; e = e.originalEvent || e; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { callback(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom) { // #4014 css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding, itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding = pick(options.padding, 8); legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox, legendGroup = item.legendGroup; if (legendGroup && legendGroup.element) { legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Set the legend item text */ setText: function (item) { var options = this.options; item.legendItem.attr({ text: options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item) }); }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( '', ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li); legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // Always update the text legend.setText(item); // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line (#915, #3976) } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Adjust the chart margins by reserving space for the legend on only one side * of the chart. If the position is set to a corner, top or bottom is reserved * for horizontal legends and left or right for vertical ones. */ adjustMargins: function (margin, spacing) { var chart = this.chart, options = this.options, // Use the first letter of each alignment option in order to detect the side alignment = options.align[0] + options.verticalAlign[0] + options.layout[0]; if (this.display && !options.floating) { each([ /(lth|ct|rth)/, /(rtv|rm|rbv)/, /(rbh|cb|lbh)/, /(lbv|lm|ltv)/ ], function (alignments, side) { if (alignments.test(alignment) && !defined(margin[side])) { // Now we have detected on which side of the chart we should reserve space for the legend chart[marginNames[side]] = mathMax( chart[marginNames[side]], chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] + pick(options.margin, 12) + spacing[side] ); } }); } }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items legend.lastLineHeight = 0; each(allItems, function (item) { legend.renderItem(item); }); // Get the box legendWidth = (options.width || legend.offsetWidth) + padding; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); legendHeight += padding; // Draw the border and/or background if (legendBorderWidth || legendBackgroundColor) { if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, lastY, allItems = this.allItems; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - this.padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - symbolHeight + 1, // #3988 legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // TODO: Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ var Chart = Highcharts.Chart = function () { this.init.apply(this, arguments); }; Chart.prototype = { /** * Hook for modules */ callbacks: [], /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // Handle updated data in the series each(series, function (serie) { if (serie.isDirty) { if (serie.options.legendType === 'point') { if (serie.updateTotals) { serie.updateTotals(); } redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Generate stacks for each series and calculate stacks total values */ getStacks: function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(titleOptions.style.fontSize, subtitle).b }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) if (!defined(widthOption)) { chart.containerWidth = adapterRun(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = adapterRun(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) : new Renderer(container, chartWidth, chartHeight, optionsChart.style); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } // Add a reference to the charts index chart.renderer.chartIndex = chart.index; }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function (skipAxes) { var chart = this, spacing = chart.spacing, margin = chart.margin, titleOffset = chart.titleOffset; chart.resetMargins(); // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend chart.legend.adjustMargins(margin, spacing); // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } if (!skipAxes) { this.getAxisMargins(); } }, getAxisMargins: function () { var chart = this, axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left margin = chart.margin; // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } // Add the axis offsets each(marginNames, function (m, side) { if (!defined(margin[side])) { chart[m] += axisOffset[side]; } }); chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win, // #805 - MooTools doesn't supply e doReflow = function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093 if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); if (e) { // Called from window.resize chart.reflowTimeout = setTimeout(doReflow, 100); } else { // Called directly (#2224) doReflow(); } } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } // Resize the container with the global animation applied if enabled (#2503) (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this; each(marginNames, function (m, side) { chart[m] = pick(chart.margin[side], chart.spacing[side]); }); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options, tempWidth, tempHeight, redoHorizontal, redoVertical; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); chart.getStacks(); // render stacks // Get chart margins chart.getMargins(true); chart.setChartSize(); // Record preliminary dimensions for later comparison tempWidth = chart.plotWidth; tempHeight = chart.plotHeight = chart.plotHeight - 13; // 13 is the most common height of X axis labels // Get margins by pre-rendering axes each(axes, function (axis) { axis.setScale(); }); chart.getAxisMargins(); // If the plot area size has changed significantly, calculate tick positions again redoHorizontal = tempWidth / chart.plotWidth > 1.1; redoVertical = tempHeight / chart.plotHeight > 1.1; if (redoHorizontal || redoVertical) { chart.maxTicks = null; // reset for second pass each(axes, function (axis) { if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) { axis.setTickInterval(true); // update to reflect the new margins } }); chart.getMargins(); // second pass to check for new labels } // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set if (Highcharts.Pointer) { chart.pointer = new Pointer(chart, options); } chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { if (chart.index !== UNDEFINED) { // Chart destroyed in its own callback (#3600) fn.apply(chart, [chart]); } }); // Fire the load event fireEvent(chart, 'load'); // If the chart was rendered outside the top container, put it back in (#3679) chart.cloneRenderTo(true); }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = { /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), i, value; for (i = 0; i < 4; ++i) { value = positions[i]; handleSlicingRoom = i < 2 || (i === 2 && /%$/.test(value)); // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 3: innerSize, relative to size positions[i] = relativeLength(value, [plotWidth, plotHeight, smallestSize, positions[2]][i]) + (handleSlicingRoom ? slicingRoom : 0); } return positions; } }; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.color = series.color; // #3445 point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret = {}, series = this.series, keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (!keys && options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); } };/** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = Highcharts.Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var options = this.options, xIncrement = this.xIncrement, date, pointInterval, pointIntervalUnit = options.pointIntervalUnit; xIncrement = pick(xIncrement, options.pointStart, 0); this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1); // Added code for pointInterval strings if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') { date = new Date(xIncrement); date = (pointIntervalUnit === 'month') ? +date[setMonth](date[getMonth]() + pointInterval) : +date[setFullYear](date[getFullYear]() + pointInterval); pointInterval = date - xIncrement; } this.xIncrement = xIncrement + pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options, zones; this.userOptions = itemOptions; // General series options take precedence over type options because otherwise, default // type options like column.animation would be overwritten by the general option. // But issues have been raised here (#3881), and the solution may be to distinguish // between default option and userOptions like in the tooltip below. options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } // Handle color zones this.zoneAxis = options.zoneAxis; zones = this.zones = (options.zones || []).slice(); if ((options.negativeColor || options.negativeFillColor) && !options.zones) { zones.push({ value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0, color: options.negativeColor, fillColor: options.negativeFillColor }); } if (zones.length) { // Push one extra zone for the rest if (defined(zones[zones.length - 1].value)) { zones.push({ color: this.color, fillColor: this.fillColor }); } } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (!this.options.colorByPoint) { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) { each(data, function (point, i) { oldData[i].update(point, false, null, false); }); } else { // Reset properties series.xIncrement = null; series.pointRange = hasCategories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); if (hasCategories && pt.name) { xAxis.names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; //series.zData = zData; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, isCartesian = series.isCartesian, xExtremes, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (xData[i] > max) { cropEnd = i + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, x, y, i, j; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = arrayMin(activeYData); this.dataMax = arrayMax(activeYData); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold, stackThreshold = options.startFromThreshold ? threshold : 0, plotX, plotY, lastPlotX, closestPointRangePx = Number.MAX_VALUE; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes (#3434) if (yAxis.isLog && yValue !== null && yValue <= 0) { point.y = yValue = null; error(10); } // Get the plotX translation point.plotX = plotX = mathMin(mathMax(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5); // #3923 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; stackValues = pointStack.points[series.index + ',' + i]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === stackThreshold) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ? mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201 UNDEFINED; point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519 plotX >= 0 && plotX <= xAxis.len; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; // Determine auto enabling of markers (#3635) if (i) { closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX)); } lastPlotX = plotX; } series.closestPointRangePx = closestPointRangePx; // now that we have the cropped data, build the segments series.getSegments(); }, /** * Set the clipping for the series. For animated series it is called twice, first to initiate * animating the clip then the second time without the animation to set the final clip. */ setClip: function (animation) { var chart = this.chart, renderer = chart.renderer, inverted = chart.inverted, seriesClipBox = this.clipBox, clipBox = seriesClipBox || chart.clipBox, sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height].join(','), clipRect = chart[sharedClipKey], markerClipRect = chart[sharedClipKey + 'm']; // If a clipping rectangle with the same properties is currently present in the chart, use that. if (!clipRect) { // When animation is set, prepare the initial positions if (animation) { clipBox.width = 0; chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox); } if (animation) { clipRect.count += 1; } if (this.options.clip !== false) { this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect); this.markerGroup.clip(markerClipRect); this.sharedClipKey = sharedClipKey; } // Remove the shared clipping rectangle when all series are shown if (!animation) { clipRect.count -= 1; if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) { if (!seriesClipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } } }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, clipRect, animation = series.options.animation, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } // Initialize the animation. Set up the clipping rectangle. if (init) { series.setClip(animation); // Run the animation } else { sharedClipKey = this.sharedClipKey; clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { this.setClip(); fireEvent(this, 'afterAnimate'); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, xAxis = series.xAxis, globallyEnabled = pick( seriesMarkerOptions.enabled, xAxis.isRadial, series.closestPointRangePx > 2 * seriesMarkerOptions.radius ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = point.isInside; // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, seriesNegativeColor = series.options.negativeColor, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, zones = series.zones, zoneAxis = series.zoneAxis || 'y', attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); // if no hover negativeColor is given, brighten the normal negativeColor stateOptionsHover.negativeColor = stateOptionsHover.negativeColor || Color(stateOptionsHover.negativeColor || seriesNegativeColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (zones.length) { var j = 0, threshold = zones[j]; while (point[zoneAxis] >= threshold.value) { threshold = zones[++j]; } point.color = point.fillColor = threshold.color; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } // Color is explicitly set to null or undefined (#1288, #4068) if (normalOptions.hasOwnProperty('color') && !normalOptions.color) { delete normalOptions.color; } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // Destroy all SVGElements associated to the series for (prop in series) { if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } } // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color, options.dashStyle]], lineWidth = options.lineWidth, roundCap = options.linecap !== 'square', graphPath = this.getGraphPath(), fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph zones = this.zones; each(zones, function (threshold, i) { props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]); }); // Draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if ((lineWidth || fillColor) && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: fillColor, zIndex: 1 // #1069 }; if (prop[2]) { attribs.dashstyle = prop[2]; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932 } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ applyZones: function () { var series = this, chart = this.chart, renderer = chart.renderer, zones = this.zones, translatedFrom, translatedTo, clips = this.clips || [], clipAttr, graph = this.graph, area = this.area, chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight), zoneAxis = this.zoneAxis || 'y', axis = this[zoneAxis + 'Axis'], extremes, reversed = axis.reversed, inverted = chart.inverted, horiz = axis.horiz, pxRange, pxPosMin, pxPosMax, ignoreZones = false; if (zones.length && (graph || area)) { // The use of the Color Threshold assumes there are no gaps // so it is safe to hide the original graph and area if (graph) { graph.hide(); } if (area) { area.hide(); } // Create the clips extremes = axis.getExtremes(); each(zones, function (threshold, i) { translatedFrom = reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(extremes.min)); translatedFrom = mathMin(mathMax(pick(translatedTo, translatedFrom), 0), chartSizeMax); translatedTo = mathMin(mathMax(mathRound(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax); if (ignoreZones) { translatedFrom = translatedTo = axis.toPixels(extremes.max); } pxRange = Math.abs(translatedFrom - translatedTo); pxPosMin = mathMin(translatedFrom, translatedTo); pxPosMax = mathMax(translatedFrom, translatedTo); if (axis.isXAxis) { clipAttr = { x: inverted ? pxPosMax : pxPosMin, y: 0, width: pxRange, height: chartSizeMax }; if (!horiz) { clipAttr.x = chart.plotHeight - clipAttr.x; } } else { clipAttr = { x: 0, y: inverted ? pxPosMax : pxPosMin, width: chartSizeMax, height: pxRange }; if (horiz) { clipAttr.y = chart.plotWidth - clipAttr.y; } } /// VML SUPPPORT if (chart.inverted && renderer.isVML) { if (axis.isXAxis) { clipAttr = { x: 0, y: reversed ? pxPosMin : pxPosMax, height: clipAttr.width, width: chart.chartWidth }; } else { clipAttr = { x: clipAttr.y - chart.plotLeft - chart.spacingBox.x, y: 0, width: clipAttr.height, height: chart.chartHeight }; } } /// END OF VML SUPPORT if (clips[i]) { clips[i].animate(clipAttr); } else { clips[i] = renderer.clipRect(clipAttr); if (graph) { series['zoneGraph' + i].clip(clips[i]); } if (area) { series['zoneArea' + i].clip(clips[i]); } } // if this zone extends out of the axis, ignore the others ignoreZones = threshold.value > extremes.max; }); this.clips = clips; } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.applyZones(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839). if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { if (animDuration) { series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animDuration); } else { series.afterAnimate(); } } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after wasDirty = series.isDirty, group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } if (wasDirty || wasDirtyData) { // #3945 recalculate the kdtree when dirty delete this.kdTree; // #3868 recalculate the kdtree with dirty data } }, /** * KD Tree && PointSearching Implementation */ kdDimensions: 1, kdAxisArray: ['clientX', 'plotY'], searchPoint: function (e, compareX) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, inverted = series.chart.inverted; return this.searchKDTree({ clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos, plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos }, compareX); }, buildKDTree: function () { var series = this, dimensions = series.kdDimensions; // Internal function function _kdtree(points, depth, dimensions) { var axis, median, length = points && points.length; if (length) { // alternate between the axis axis = series.kdAxisArray[depth % dimensions]; // sort point array points.sort(function(a, b) { return a[axis] - b[axis]; }); median = Math.floor(length / 2); // build and return nod return { point: points[median], left: _kdtree(points.slice(0, median), depth + 1, dimensions), right: _kdtree(points.slice(median + 1), depth + 1, dimensions) }; } } // Start the recursive build process with a clone of the points array and null points filtered out (#3873) function startRecursive() { var points = grep(series.points, function (point) { return point.y !== null; }); series.kdTree = _kdtree(points, dimensions, dimensions); } delete series.kdTree; if (series.options.kdSync) { // For testing tooltips, don't build async startRecursive(); } else { setTimeout(startRecursive); } }, searchKDTree: function (point, compareX) { var series = this, kdX = this.kdAxisArray[0], kdY = this.kdAxisArray[1], kdComparer = compareX ? 'distX' : 'dist'; // Set the one and two dimensional distance on the point object function setDistance(p1, p2) { var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null, y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null, r = (x || 0) + (y || 0); p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE; p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE; } function _search(search, tree, depth, dimensions) { var point = tree.point, axis = series.kdAxisArray[depth % dimensions], tdist, sideA, sideB, ret = point, nPoint1, nPoint2; setDistance(search, point); // Pick side based on distance to splitting point tdist = search[axis] - point[axis]; sideA = tdist < 0 ? 'left' : 'right'; sideB = tdist < 0 ? 'right' : 'left'; // End of tree if (tree[sideA]) { nPoint1 =_search(search, tree[sideA], depth + 1, dimensions); ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point); } if (tree[sideB]) { // compare distance to current best to splitting point to decide wether to check side B or not if (Math.sqrt(tdist * tdist) < ret[kdComparer]) { nPoint2 = _search(search, tree[sideB], depth + 1, dimensions); ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret); } } return ret; } if (!this.kdTree) { this.buildKDTree(); } if (this.kdTree) { return _search(point, this.kdTree, this.kdDimensions, this.kdDimensions); } } }; // end Series prototype /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Initialize total value this.total = null; // This will keep each points' extremes stored by series.index and point index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, reversed = axis.reversed, neg = (this.isNegative && !reversed) || (!this.isNegative && reversed), // #4056 y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true); } } }; // Stacking methods defined on the Axis prototype /** * Build the stacks from top down */ Axis.prototype.buildStacks = function () { var series = this.series, reversedStacks = pick(this.options.reversedStacks, true), i = series.length; if (!this.isXAxis) { this.usePercentage = false; while (i--) { series[reversedStacks ? i : series.length - i - 1].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }; Axis.prototype.renderStackTotals = function () { var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } }; // Stacking methods defnied for Series prototype /** * Adds series' points value to corresponding stack */ Series.prototype.setStackedPoints = function () { if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) { return; } var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackThreshold = seriesOptions.startFromThreshold ? threshold : 0, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, isNegative, stack, other, key, pointKey, i, x, y; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; pointKey = series.index + ',' + i; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) isNegative = negStacks && y < (stackThreshold ? 0 : threshold); key = isNegative ? negKey : stackKey; // Create empty object for this stack if it doesn't exist yet if (!stacks[key]) { stacks[key] = {}; } // Initialize StackItem for this x if (!stacks[key][x]) { if (oldStacks[key] && oldStacks[key][x]) { stacks[key][x] = oldStacks[key][x]; stacks[key][x].total = null; } else { stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; //stack.points[pointKey] = [stack.cum || stackThreshold]; stack.points[pointKey] = [pick(stack.cum, stackThreshold)]; // Add value to the stack total if (stacking === 'percent') { // Percent stacked column, totals are the same for the positive and negative stacks other = isNegative ? stackKey : negKey; if (negStacks && stacks[other] && stacks[other][x]) { other = stacks[other][x]; stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0; // Percent stacked areas } else { stack.total = correctFloat(stack.total + (mathAbs(y) || 0)); } } else { stack.total = correctFloat(stack.total + (y || 0)); } stack.cum = pick(stack.cum, stackThreshold) + (y || 0); stack.points[pointKey].push(stack.cum); stackedYData[i] = stack.cum; } if (stacking === 'percent') { yAxis.usePercentage = true; } this.stackedYData = stackedYData; // To be used in getExtremes // Reset old stacks yAxis.oldStacks = {}; }; /** * Iterate over all stacks and compute the absolute values to percent */ Series.prototype.setPercentStacks = function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData; each([stackKey, '-' + stackKey], function (key) { var i = processedXData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = processedXData[i]; stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[series.index + ',' + i]; if (pointExtremes) { totalFactor = stack.total ? 100 / stack.total : 0; pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value series.stackedYData[i] = pointExtremes[1]; } } }); }; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length, isX: isX })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options, names = series.xAxis && series.xAxis.names; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (point.y === null && graphic) { // #4146 point.graphic = graphic.destroy(); } if (isObject(options) && !isArray(options)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } else { graphic.attr(point.pointAttr[point.state || ''])[point.visible ? 'show' : 'hide'](true); // #2430 } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); if (names && point.name) { names[point.x] = point.name; } seriesOptions.data[i] = point.options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.isDirtyLegend = true; } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { this.series.removePoint(inArray(this, this.series.data), redraw, animation); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, shiftShapes = ['graph', 'area'], dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, i, x; setAnimation(animation, chart); // Make graph animate sideways if (shift) { i = series.zones.length; while (i--) { shiftShapes.push('zoneGraph' + i, 'zoneArea' + i); } each(shiftShapes, function (shape) { if (series[shape]) { series[shape].shift = currentShift + 1; } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Remove a point (rendered or not), by index */ removePoint: function (i, redraw, animation) { var series = this, data = series.data, point = data[i], points = series.points, chart = series.chart, remove = function () { if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point || { series: series }, 'splice', i, 1); if (point) { point.destroy(); } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }; setAnimation(animation, chart); redraw = pick(redraw, true); // Fire the event with a default handler of removing the point if (point) { point.firePointEvent('remove', null, remove); } else { remove(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // If we're changing type or zIndex, create new groups (#3380, #3404) if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) { preserve.length = 0; } // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and delete all properties. Reinsert all methods // and properties from the new type prototype (#2270, #3719) this.remove(false); for (n in proto) { this[n] = UNDEFINED; } extend(this, seriesTypes[newOptions.type || oldType].prototype); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = UNDEFINED; // #1611, #2887 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var series = this, segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336) keys.push(+x); } } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { var y = 0, stackPoint; if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836 return; // The point exists, push it to the segment } else if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { // Loop down the stack to find the series below this one that has // a value (#1991) for (i = series.index; i <= yAxis.series.length; i++) { stackPoint = stack[x].points[i + ',' + x]; if (stackPoint) { y = stackPoint[1]; break; } } plotX = xAxis.translate(x); plotY = yAxis.toPixels(y, true); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length, translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181 yBottom; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { yBottom = pick(segment[i].yBottom, translatedThreshold); // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, yBottom); } areaSegmentPath.push(segment[i].plotX, yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment, translatedThreshold); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment, translatedThreshold) { path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, zones = this.zones, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color each(zones, function (threshold, i) { props.push(['zoneArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]); }); each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.area = AreaSeries; /** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', //borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, startFromThreshold: true, // docs: http://jsfiddle.net/highcharts/hz8fopan/14/ stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1; if (chart.inverted) { translatedThreshold -= 0.5; // #3355 if (chart.renderer.isVML) { yCrisp += 1; } } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function (point) { var yBottom = pick(point.yBottom, translatedThreshold), safeDistance = 999 + mathAbs(yBottom), plotY = mathMin(mathMax(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), right, bottom, fromTop, up, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative); barY = mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (up ? minPointLength : 0)); // #1485, #4051 } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Round off to obtain crisp edges and avoid overlapping with neighbours (#2694) right = mathRound(barX + barW) + xCrisp; barX = mathRound(barX) + xCrisp; barW = right - barX; fromTop = mathAbs(barY) < 0.5; bottom = mathMin(mathRound(barY + barH) + yCrisp, 9e4); // #3575 barY = mathRound(barY) + yCrisp; barH = bottom - barY; // Top edges are exceptions if (fromTop) { barY -= 1; barH += 1; } // Fix the tooltip on center of grouped columns (#1216, #424, #3648) point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH]; // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = { x: barX, y: barY, width: barW, height: barH }; }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(borderAttr) .attr(pointAttr) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, marker: { enabled: true // Overrides auto-enabling in line series (#3647) }, tooltip: { headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' } }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 kdDimensions: 2, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { // #2945 return this.point.name; }, // softConnector: true, x: 0 // y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function (e) { point.slice(e.type === 'select'); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis, redraw) { var point = this, series = point.series, chart = series.chart, ignoreHiddenPoint = series.options.ignoreHiddenPoint; redraw = pick(redraw, ignoreHiddenPoint); if (vis !== point.visible) { // If called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data // Show and hide associated elements. This is performed regardless of redraw or not, // because chart.redraw only handles full series. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][vis ? 'show' : 'hide'](true); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (ignoreHiddenPoint) { series.isDirty = true; } if (redraw) { chart.redraw(); } } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } }, haloPath: function (size) { var shapeArgs = this.shapeArgs, chart = this.series.chart; return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, { innerR: this.shapeArgs.r, start: shapeArgs.start, end: shapeArgs.end }); } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, directTouch: true, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], axisTypes: [], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Pies have one color each point */ getColor: noop, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: point.startR || (series.center[3] / 2), // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw, animation, updatePoints) { Series.prototype.setData.call(this, data, false, animation, updatePoints); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(animation); } }, /** * Recompute total chart sum and update percentages of points. */ updateTotals: function () { var i, total = 0, points = this.points, len = points.length, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; // Get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } this.total = total; // Set each point's properties for (i = 0; i < len; i++) { point = points[i]; point.percentage = (total > 0 && (point.visible || !ignoreHiddenPoint)) ? point.y / total * 100 : 0; point.total = total; } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { Series.prototype.generatePoints.call(this); this.updateTotals(); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngle = options.startAngle || 0, startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90), endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90), circ = endAngleRad - startAngleRad, //2 * mathPI, points = series.points, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle start = startAngleRad + (cumulative * circ); if (!ignoreHiddenPoint || point.visible) { cumulative += point.percentage / 100; } end = startAngleRad + (cumulative * circ); // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: mathRound(start * precision) / precision, end: mathRound(end * precision) / precision }; // The angle must stay within -90 and 270 (#2645) angle = (end + start) / 2; if (angle > 1.5 * mathPI) { angle -= 2 * mathPI; } else if (angle < -mathPI / 2) { angle += 2 * mathPI; } // Center for the sliced out slice point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; } }, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs, attr; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic.animate(extend(shapeArgs, groupTranslation)); } else { attr = { 'stroke-linejoin': 'round' }; if (!point.visible) { attr.visibility = 'hidden'; } point.graphic = graphic = renderer[point.shapeType](shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr(attr) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } }); }, searchPoint: noop, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Use a simple symbol from LegendSymbolMixin */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Use the getCenter method from drawLegendSymbol */ getCenter: CenteredSeriesMixin.getCenter, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup, renderer = series.chart.renderer; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', options.defer ? HIDDEN : VISIBLE, options.zIndex || 6 ); if (pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #3023, #3024 dataLabelsGroup.show(); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true, style, moreStyle = {}; // Determine if each data label is enabled pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); style = options.style; rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color style.color = pick(options.color, style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Get automated contrast color if (style.color === 'contrast') { moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ? renderer.getContrast(point.color || series.color) : '#000000'; } if (cursor) { moreStyle.cursor = cursor; } // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, options.shape, null, null, options.useHTML ) .attr(attr) .css(extend(style, moreStyle)) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), baseline = chart.renderer.fontMetrics(options.style.fontSize).b, rotCorr, // rotation correction // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr; // the final position; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text rotCorr = chart.renderer.rotCorr(baseline, options.rotation); // #3723 dataLabel[isNew ? 'attr' : 'animate']({ x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x, y: alignTo.y + options.y + alignTo.height / 2 }) .attr({ // #3003 align: options.align }); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === 'justify') { this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); } else if (pick(options.crop, true)) { // Now check that the data label is within the plot area visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } // When we're using a shape, make it possible with a connector or an arrow pointing to thie point if (options.shape) { dataLabel.attr({ anchorX: point.plotX, anchorY: point.plotY }); } } } // Show or hide based on the final aligned position if (!visible) { dataLabel.attr({ y: -999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified, padding = dataLabel.box ? 0 : (dataLabel.padding || 0); // Off left off = alignAttr.x + padding; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width - padding; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y + padding; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height - padding; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 halves[point.half].push(point); } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : 'inherit'; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = mathMin(mathMax(0, naturalY), chart.plotHeight); } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos && point.visible) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel && point.visible) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; center[3] = relativeLength(options.innerSize || 0, newSize); this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var inverted = this.chart.inverted, series = point.series, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: series.yAxis.len - alignTo.y - alignTo.height, y: series.xAxis.len - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * Highstock JS v2.1.6 (2015-06-12) * Highcharts module to hide overlapping data labels. This module is included by default in Highmaps. * * (c) 2010-2014 Torstein Honsi * * License: www.highcharts.com/license */ /*global Highcharts, HighchartsAdapter */ (function (H) { var Chart = H.Chart, each = H.each, pick = H.pick, addEvent = HighchartsAdapter.addEvent; // Collect potensial overlapping data labels. Stack labels probably don't need to be // considered because they are usually accompanied by data labels that lie inside the columns. Chart.prototype.callbacks.push(function (chart) { function collectAndHide() { var labels = []; each(chart.series, function (series) { var dlOptions = series.options.dataLabels; if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866 each(series.points, function (point) { if (point.dataLabel) { point.dataLabel.labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118 labels.push(point.dataLabel); } }); } }); chart.hideOverlappingLabels(labels); } // Do it now ... collectAndHide(); // ... and after each chart redraw addEvent(chart, 'redraw', collectAndHide); }); /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ Chart.prototype.hideOverlappingLabels = function (labels) { var len = labels.length, label, i, j, label1, label2, intersectRect = function (pos1, pos2, size1, size2) { return !( pos2.x > pos1.x + size1.width || pos2.x + size2.width < pos1.x || pos2.y > pos1.y + size1.height || pos2.y + size2.height < pos1.y ); }; // Mark with initial opacity for (i = 0; i < len; i++) { label = labels[i]; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } } // Prevent a situation in a gradually rising slope, that each label // will hide the previous one because the previous one always has // lower rank. labels.sort(function (a, b) { return b.labelrank - a.labelrank; }); // Detect overlapping labels for (i = 0; i < len; i++) { label1 = labels[i]; for (j = i + 1; j < len; ++j) { label2 = labels[j]; if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0 && intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) { (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0; } } } // Hide or show for (i = 0; i < len; i++) { label = labels[i]; if (label) { if (label.oldOpacity !== label.newOpacity && label.placed) { label.alignAttr.opacity = label.newOpacity; label[label.isOld && label.newOpacity ? 'animate' : 'attr'](label.alignAttr); } label.isOld = true; } } }; }(Highcharts));/** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item.series || item, 'checkboxClick', { // #3712 checked: target.checked, item: item }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var mousePos = e[isX ? 'chartX' : 'chartY'], axis = chart[isX ? 'xAxis' : 'yAxis'][0], startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange, goingLeft = startPos > mousePos; // #3613 if (axis.series.length && (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) && (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; if (chart.hoverSeries !== series) { series.onMouseOver(); } // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(chart.seriesGroup); } halo.attr(extend({ fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get() }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted; return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; chart.hoverSeries = null; // #182, set to null before the mouseOut event fires // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, stateOptions = options.states, lineWidth = options.lineWidth, attribs, i = 0; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); // #4035 } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); while (series['zoneGraph' + i]) { series['zoneGraph' + i].attr(attribs); i = i + 1; } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph });/* **************************************************************************** * Start ordinal axis logic * *****************************************************************************/ wrap(Series.prototype, 'init', function (proceed) { var series = this, xAxis; // call the original function proceed.apply(this, Array.prototype.slice.call(arguments, 1)); xAxis = series.xAxis; // Destroy the extended ordinal index on updated data if (xAxis && xAxis.options.ordinal) { addEvent(series, 'updatedData', function () { delete xAxis.ordinalIndex; }); } }); /** * In an ordinal axis, there might be areas with dense consentrations of points, then large * gaps between some. Creating equally distributed ticks over this entire range * may lead to a huge number of ticks that will later be removed. So instead, break the * positions up in segments, find the tick positions for each segment then concatenize them. * This method is used from both data grouping logic and X axis tick position logic. */ wrap(Axis.prototype, 'getTimeTicks', function (proceed, normalizedInterval, min, max, startOfWeek, positions, closestDistance, findHigherRanks) { var start = 0, end = 0, segmentPositions, higherRanks = {}, hasCrossedHigherRank, info, posLength, outsideMax, groupPositions = [], lastGroupPosition = -Number.MAX_VALUE, tickPixelIntervalOption = this.options.tickPixelInterval; // The positions are not always defined, for example for ordinal positions when data // has regular interval (#1557, #2090) if ((!this.options.ordinal && !this.options.breaks) || !positions || positions.length < 3 || min === UNDEFINED) { return proceed.call(this, normalizedInterval, min, max, startOfWeek); } // Analyze the positions array to split it into segments on gaps larger than 5 times // the closest distance. The closest distance is already found at this point, so // we reuse that instead of computing it again. posLength = positions.length; for (; end < posLength; end++) { outsideMax = end && positions[end - 1] > max; if (positions[end] < min) { // Set the last position before min start = end; } if (end === posLength - 1 || positions[end + 1] - positions[end] > closestDistance * 5 || outsideMax) { // For each segment, calculate the tick positions from the getTimeTicks utility // function. The interval will be the same regardless of how long the segment is. if (positions[end] > lastGroupPosition) { // #1475 segmentPositions = proceed.call(this, normalizedInterval, positions[start], positions[end], startOfWeek); // Prevent duplicate groups, for example for multiple segments within one larger time frame (#1475) while (segmentPositions.length && segmentPositions[0] <= lastGroupPosition) { segmentPositions.shift(); } if (segmentPositions.length) { lastGroupPosition = segmentPositions[segmentPositions.length - 1]; } groupPositions = groupPositions.concat(segmentPositions); } // Set start of next segment start = end + 1; } if (outsideMax) { break; } } // Get the grouping info from the last of the segments. The info is the same for // all segments. info = segmentPositions.info; // Optionally identify ticks with higher rank, for example when the ticks // have crossed midnight. if (findHigherRanks && info.unitRange <= timeUnits.hour) { end = groupPositions.length - 1; // Compare points two by two for (start = 1; start < end; start++) { if (dateFormat('%d', groupPositions[start]) !== dateFormat('%d', groupPositions[start - 1])) { higherRanks[groupPositions[start]] = 'day'; hasCrossedHigherRank = true; } } // If the complete array has crossed midnight, we want to mark the first // positions also as higher rank if (hasCrossedHigherRank) { higherRanks[groupPositions[0]] = 'day'; } info.higherRanks = higherRanks; } // Save the info groupPositions.info = info; // Don't show ticks within a gap in the ordinal axis, where the space between // two points is greater than a portion of the tick pixel interval if (findHigherRanks && defined(tickPixelIntervalOption)) { // check for squashed ticks var length = groupPositions.length, i = length, itemToRemove, translated, translatedArr = [], lastTranslated, medianDistance, distance, distances = []; // Find median pixel distance in order to keep a reasonably even distance between // ticks (#748) while (i--) { translated = this.translate(groupPositions[i]); if (lastTranslated) { distances[i] = lastTranslated - translated; } translatedArr[i] = lastTranslated = translated; } distances.sort(); medianDistance = distances[mathFloor(distances.length / 2)]; if (medianDistance < tickPixelIntervalOption * 0.6) { medianDistance = null; } // Now loop over again and remove ticks where needed i = groupPositions[length - 1] > max ? length - 1 : length; // #817 lastTranslated = undefined; while (i--) { translated = translatedArr[i]; distance = lastTranslated - translated; // Remove ticks that are closer than 0.6 times the pixel interval from the one to the right, // but not if it is close to the median distance (#748). if (lastTranslated && distance < tickPixelIntervalOption * 0.8 && (medianDistance === null || distance < medianDistance * 0.8)) { // Is this a higher ranked position with a normal position to the right? if (higherRanks[groupPositions[i]] && !higherRanks[groupPositions[i + 1]]) { // Yes: remove the lower ranked neighbour to the right itemToRemove = i + 1; lastTranslated = translated; // #709 } else { // No: remove this one itemToRemove = i; } groupPositions.splice(itemToRemove, 1); } else { lastTranslated = translated; } } } return groupPositions; }); // Extend the Axis prototype extend(Axis.prototype, { /** * Calculate the ordinal positions before tick positions are calculated. */ beforeSetTickPositions: function () { var axis = this, len, ordinalPositions = [], useOrdinal = false, dist, extremes = axis.getExtremes(), min = extremes.min, max = extremes.max, minIndex, maxIndex, slope, hasBreaks = axis.isXAxis && !!axis.options.breaks, isOrdinal = axis.options.ordinal, i; // apply the ordinal logic if (isOrdinal || hasBreaks) { // #4167 YAxis is never ordinal ? each(axis.series, function (series, i) { if (series.visible !== false && (series.takeOrdinalPosition !== false || hasBreaks)) { // concatenate the processed X data into the existing positions, or the empty array ordinalPositions = ordinalPositions.concat(series.processedXData); len = ordinalPositions.length; // remove duplicates (#1588) ordinalPositions.sort(function (a, b) { return a - b; // without a custom function it is sorted as strings }); if (len) { i = len - 1; while (i--) { if (ordinalPositions[i] === ordinalPositions[i + 1]) { ordinalPositions.splice(i, 1); } } } } }); // cache the length len = ordinalPositions.length; // Check if we really need the overhead of mapping axis data against the ordinal positions. // If the series consist of evenly spaced data any way, we don't need any ordinal logic. if (len > 2) { // two points have equal distance by default dist = ordinalPositions[1] - ordinalPositions[0]; i = len - 1; while (i-- && !useOrdinal) { if (ordinalPositions[i + 1] - ordinalPositions[i] !== dist) { useOrdinal = true; } } // When zooming in on a week, prevent axis padding for weekends even though the data within // the week is evenly spaced. if (!axis.options.keepOrdinalPadding && (ordinalPositions[0] - min > dist || max - ordinalPositions[ordinalPositions.length - 1] > dist)) { useOrdinal = true; } } // Record the slope and offset to compute the linear values from the array index. // Since the ordinal positions may exceed the current range, get the start and // end positions within it (#719, #665b) if (useOrdinal) { // Register axis.ordinalPositions = ordinalPositions; // This relies on the ordinalPositions being set. Use mathMax and mathMin to prevent // padding on either sides of the data. minIndex = axis.val2lin(mathMax(min, ordinalPositions[0]), true); maxIndex = mathMax(axis.val2lin(mathMin(max, ordinalPositions[ordinalPositions.length - 1]), true), 1); // #3339 // Set the slope and offset of the values compared to the indices in the ordinal positions axis.ordinalSlope = slope = (max - min) / (maxIndex - minIndex); axis.ordinalOffset = min - (minIndex * slope); } else { axis.ordinalPositions = axis.ordinalSlope = axis.ordinalOffset = UNDEFINED; } } axis.doPostTranslate = (isOrdinal && useOrdinal) || hasBreaks; // #3818, #4196 axis.groupIntervalFactor = null; // reset for next run }, /** * Translate from a linear axis value to the corresponding ordinal axis position. If there * are no gaps in the ordinal axis this will be the same. The translated value is the value * that the point would have if the axis were linear, using the same min and max. * * @param Number val The axis value * @param Boolean toIndex Whether to return the index in the ordinalPositions or the new value */ val2lin: function (val, toIndex) { var axis = this, ordinalPositions = axis.ordinalPositions; if (!ordinalPositions) { return val; } else { var ordinalLength = ordinalPositions.length, i, distance, ordinalIndex; // first look for an exact match in the ordinalpositions array i = ordinalLength; while (i--) { if (ordinalPositions[i] === val) { ordinalIndex = i; break; } } // if that failed, find the intermediate position between the two nearest values i = ordinalLength - 1; while (i--) { if (val > ordinalPositions[i] || i === 0) { // interpolate distance = (val - ordinalPositions[i]) / (ordinalPositions[i + 1] - ordinalPositions[i]); // something between 0 and 1 ordinalIndex = i + distance; break; } } return toIndex ? ordinalIndex : axis.ordinalSlope * (ordinalIndex || 0) + axis.ordinalOffset; } }, /** * Translate from linear (internal) to axis value * * @param Number val The linear abstracted value * @param Boolean fromIndex Translate from an index in the ordinal positions rather than a value */ lin2val: function (val, fromIndex) { var axis = this, ordinalPositions = axis.ordinalPositions; if (!ordinalPositions) { // the visible range contains only equally spaced values return val; } else { var ordinalSlope = axis.ordinalSlope, ordinalOffset = axis.ordinalOffset, i = ordinalPositions.length - 1, linearEquivalentLeft, linearEquivalentRight, distance; // Handle the case where we translate from the index directly, used only // when panning an ordinal axis if (fromIndex) { if (val < 0) { // out of range, in effect panning to the left val = ordinalPositions[0]; } else if (val > i) { // out of range, panning to the right val = ordinalPositions[i]; } else { // split it up i = mathFloor(val); distance = val - i; // the decimal } // Loop down along the ordinal positions. When the linear equivalent of i matches // an ordinal position, interpolate between the left and right values. } else { while (i--) { linearEquivalentLeft = (ordinalSlope * i) + ordinalOffset; if (val >= linearEquivalentLeft) { linearEquivalentRight = (ordinalSlope * (i + 1)) + ordinalOffset; distance = (val - linearEquivalentLeft) / (linearEquivalentRight - linearEquivalentLeft); // something between 0 and 1 break; } } } // If the index is within the range of the ordinal positions, return the associated // or interpolated value. If not, just return the value return distance !== UNDEFINED && ordinalPositions[i] !== UNDEFINED ? ordinalPositions[i] + (distance ? distance * (ordinalPositions[i + 1] - ordinalPositions[i]) : 0) : val; } }, /** * Get the ordinal positions for the entire data set. This is necessary in chart panning * because we need to find out what points or data groups are available outside the * visible range. When a panning operation starts, if an index for the given grouping * does not exists, it is created and cached. This index is deleted on updated data, so * it will be regenerated the next time a panning operation starts. */ getExtendedPositions: function () { var axis = this, chart = axis.chart, grouping = axis.series[0].currentDataGrouping, ordinalIndex = axis.ordinalIndex, key = grouping ? grouping.count + grouping.unitName : 'raw', extremes = axis.getExtremes(), fakeAxis, fakeSeries; // If this is the first time, or the ordinal index is deleted by updatedData, // create it. if (!ordinalIndex) { ordinalIndex = axis.ordinalIndex = {}; } if (!ordinalIndex[key]) { // Create a fake axis object where the extended ordinal positions are emulated fakeAxis = { series: [], getExtremes: function () { return { min: extremes.dataMin, max: extremes.dataMax }; }, options: { ordinal: true }, val2lin: Axis.prototype.val2lin // #2590 }; // Add the fake series to hold the full data, then apply processData to it each(axis.series, function (series) { fakeSeries = { xAxis: fakeAxis, xData: series.xData, chart: chart, destroyGroupedData: noop }; fakeSeries.options = { dataGrouping : grouping ? { enabled: true, forced: true, approximation: 'open', // doesn't matter which, use the fastest units: [[grouping.unitName, [grouping.count]]] } : { enabled: false } }; series.processData.apply(fakeSeries); fakeAxis.series.push(fakeSeries); }); // Run beforeSetTickPositions to compute the ordinalPositions axis.beforeSetTickPositions.apply(fakeAxis); // Cache it ordinalIndex[key] = fakeAxis.ordinalPositions; } return ordinalIndex[key]; }, /** * Find the factor to estimate how wide the plot area would have been if ordinal * gaps were included. This value is used to compute an imagined plot width in order * to establish the data grouping interval. * * A real world case is the intraday-candlestick * example. Without this logic, it would show the correct data grouping when viewing * a range within each day, but once moving the range to include the gap between two * days, the interval would include the cut-away night hours and the data grouping * would be wrong. So the below method tries to compensate by identifying the most * common point interval, in this case days. * * An opposite case is presented in issue #718. We have a long array of daily data, * then one point is appended one hour after the last point. We expect the data grouping * not to change. * * In the future, if we find cases where this estimation doesn't work optimally, we * might need to add a second pass to the data grouping logic, where we do another run * with a greater interval if the number of data groups is more than a certain fraction * of the desired group count. */ getGroupIntervalFactor: function (xMin, xMax, series) { var i = 0, processedXData = series.processedXData, len = processedXData.length, distances = [], median, groupIntervalFactor = this.groupIntervalFactor; // Only do this computation for the first series, let the other inherit it (#2416) if (!groupIntervalFactor) { // Register all the distances in an array for (; i < len - 1; i++) { distances[i] = processedXData[i + 1] - processedXData[i]; } // Sort them and find the median distances.sort(function (a, b) { return a - b; }); median = distances[mathFloor(len / 2)]; // Compensate for series that don't extend through the entire axis extent. #1675. xMin = mathMax(xMin, processedXData[0]); xMax = mathMin(xMax, processedXData[len - 1]); this.groupIntervalFactor = groupIntervalFactor = (len * median) / (xMax - xMin); } // Return the factor needed for data grouping return groupIntervalFactor; }, /** * Make the tick intervals closer because the ordinal gaps make the ticks spread out or cluster */ postProcessTickInterval: function (tickInterval) { // TODO: http://jsfiddle.net/highcharts/FQm4E/1/ // This is a case where this algorithm doesn't work optimally. In this case, the // tick labels are spread out per week, but all the gaps reside within weeks. So // we have a situation where the labels are courser than the ordinal gaps, and // thus the tick interval should not be altered var ordinalSlope = this.ordinalSlope; if (ordinalSlope) { if (!this.options.breaks) { return tickInterval / (ordinalSlope / this.closestPointRange); } else { return this.closestPointRange; } } else { return tickInterval; } } }); // Extending the Chart.pan method for ordinal axes wrap(Chart.prototype, 'pan', function (proceed, e) { var chart = this, xAxis = chart.xAxis[0], chartX = e.chartX, runBase = false; if (xAxis.options.ordinal && xAxis.series.length) { var mouseDownX = chart.mouseDownX, extremes = xAxis.getExtremes(), dataMax = extremes.dataMax, min = extremes.min, max = extremes.max, trimmedRange, hoverPoints = chart.hoverPoints, closestPointRange = xAxis.closestPointRange, pointPixelWidth = xAxis.translationSlope * (xAxis.ordinalSlope || closestPointRange), movedUnits = (mouseDownX - chartX) / pointPixelWidth, // how many ordinal units did we move? extendedAxis = { ordinalPositions: xAxis.getExtendedPositions() }, // get index of all the chart's points ordinalPositions, searchAxisLeft, lin2val = xAxis.lin2val, val2lin = xAxis.val2lin, searchAxisRight; if (!extendedAxis.ordinalPositions) { // we have an ordinal axis, but the data is equally spaced runBase = true; } else if (mathAbs(movedUnits) > 1) { // Remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (movedUnits < 0) { searchAxisLeft = extendedAxis; searchAxisRight = xAxis.ordinalPositions ? xAxis : extendedAxis; } else { searchAxisLeft = xAxis.ordinalPositions ? xAxis : extendedAxis; searchAxisRight = extendedAxis; } // In grouped data series, the last ordinal position represents the grouped data, which is // to the left of the real data max. If we don't compensate for this, we will be allowed // to pan grouped data series passed the right of the plot area. ordinalPositions = searchAxisRight.ordinalPositions; if (dataMax > ordinalPositions[ordinalPositions.length - 1]) { ordinalPositions.push(dataMax); } // Get the new min and max values by getting the ordinal index for the current extreme, // then add the moved units and translate back to values. This happens on the // extended ordinal positions if the new position is out of range, else it happens // on the current x axis which is smaller and faster. chart.fixedRange = max - min; trimmedRange = xAxis.toFixedRange(null, null, lin2val.apply(searchAxisLeft, [ val2lin.apply(searchAxisLeft, [min, true]) + movedUnits, // the new index true // translate from index ]), lin2val.apply(searchAxisRight, [ val2lin.apply(searchAxisRight, [max, true]) + movedUnits, // the new index true // translate from index ]) ); // Apply it if it is within the available data range if (trimmedRange.min >= mathMin(extremes.dataMin, min) && trimmedRange.max <= mathMax(dataMax, max)) { xAxis.setExtremes(trimmedRange.min, trimmedRange.max, true, false, { trigger: 'pan' }); } chart.mouseDownX = chartX; // set new reference for next run css(chart.container, { cursor: 'move' }); } } else { runBase = true; } // revert to the linear chart.pan version if (runBase) { // call the original function proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } }); /** * Extend getSegments by identifying gaps in the ordinal data so that we can draw a gap in the * line or area */ wrap(Series.prototype, 'getSegments', function (proceed) { var series = this, segments, gapSize = series.options.gapSize, xAxis = series.xAxis; // call base method proceed.apply(this, Array.prototype.slice.call(arguments, 1)); if (gapSize) { // properties segments = series.segments; // extension for ordinal breaks each(segments, function (segment, no) { var i = segment.length - 1; while (i--) { if (segment[i + 1].x - segment[i].x > xAxis.closestPointRange * gapSize) { segments.splice( // insert after this one no + 1, 0, segment.splice(i + 1, segment.length - i) ); } } }); } }); /* **************************************************************************** * End ordinal axis logic * *****************************************************************************/ /** * Highstock JS v2.1.6 (2015-06-12) * Highcharts Broken Axis module * * Author: Stephane Vanraes, Torstein Honsi * License: www.highcharts.com/license */ /*global HighchartsAdapter*/ (function (H) { "use strict"; var pick = H.pick, wrap = H.wrap, extend = H.extend, fireEvent = HighchartsAdapter.fireEvent, Axis = H.Axis, Series = H.Series; function stripArguments() { return Array.prototype.slice.call(arguments, 1); } extend(Axis.prototype, { isInBreak: function (brk, val) { var repeat = brk.repeat || Infinity, from = brk.from, length = brk.to - brk.from, test = (val >= from ? (val - from) % repeat : repeat - ((from - val) % repeat)); if (!brk.inclusive) { return (test < length && test !== 0); } else { return (test <= length); } }, isInAnyBreak: function (val, testKeep) { // Sanity Check if (!this.options.breaks) { return false; } var breaks = this.options.breaks, i = breaks.length, inbrk = false, keep = false; while (i--) { if (this.isInBreak(breaks[i], val)) { inbrk = true; if (!keep) { keep = pick(breaks[i].showPoints, this.isXAxis ? false : true); } } } if (inbrk && testKeep) { return inbrk && !keep; } else { return inbrk; } } }); wrap(Axis.prototype, 'setTickPositions', function (proceed) { proceed.apply(this, Array.prototype.slice.call(arguments, 1)); if (this.options.breaks) { var axis = this, tickPositions = this.tickPositions, info = this.tickPositions.info, newPositions = [], i; if (info && info.totalRange >= axis.closestPointRange) { return; } for (i = 0; i < tickPositions.length; i++) { if (!axis.isInAnyBreak(tickPositions[i])) { newPositions.push(tickPositions[i]); } } this.tickPositions = newPositions; this.tickPositions.info = info; } }); wrap(Axis.prototype, 'init', function (proceed, chart, userOptions) { // Force Axis to be not-ordinal when breaks are defined if (userOptions.breaks && userOptions.breaks.length) { userOptions.ordinal = false; } proceed.call(this, chart, userOptions); if (this.options.breaks) { var axis = this; axis.doPostTranslate = true; this.val2lin = function (val) { var nval = val, brk, i; for (i = 0; i < axis.breakArray.length; i++) { brk = axis.breakArray[i]; if (brk.to <= val) { nval -= (brk.len); } else if (brk.from >= val) { break; } else if (axis.isInBreak(brk, val)) { nval -= (val - brk.from); break; } } return nval; }; this.lin2val = function (val) { var nval = val, brk, i; for (i = 0; i < axis.breakArray.length; i++) { brk = axis.breakArray[i]; if (brk.from >= nval) { break; } else if (brk.to < nval) { nval += (brk.to - brk.from); } else if (axis.isInBreak(brk, nval)) { nval += (brk.to - brk.from); } } return nval; }; this.setExtremes = function (newMin, newMax, redraw, animation, eventArguments) { // If trying to set extremes inside a break, extend it to before and after the break ( #3857 ) while (this.isInAnyBreak(newMin)) { newMin -= this.closestPointRange; } while (this.isInAnyBreak(newMax)) { newMax -= this.closestPointRange; } Axis.prototype.setExtremes.call(this, newMin, newMax, redraw, animation, eventArguments); }; this.setAxisTranslation = function (saveOld) { Axis.prototype.setAxisTranslation.call(this, saveOld); var breaks = axis.options.breaks, breakArrayT = [], // Temporary one breakArray = [], length = 0, inBrk, repeat, brk, min = axis.userMin || axis.min, max = axis.userMax || axis.max, start, i, j; // Min & max check (#4247) for (i in breaks) { brk = breaks[i]; repeat = brk.repeat || Infinity; if (axis.isInBreak(brk, min)) { min += (brk.to % repeat) - (min % repeat); } if (axis.isInBreak(brk, max)) { max -= (max % repeat) - (brk.from % repeat); } } // Construct an array holding all breaks in the axis for (i in breaks) { brk = breaks[i]; start = brk.from; repeat = brk.repeat || Infinity; while (start - repeat > min) { start -= repeat; } while (start < min) { start += repeat; } for (j = start; j < max; j += repeat) { breakArrayT.push({ value: j, move: 'in' }); breakArrayT.push({ value: j + (brk.to - brk.from), move: 'out', size: brk.breakSize }); } } breakArrayT.sort(function (a, b) { if (a.value === b.value) { return (a.move === 'in' ? 0 : 1) - (b.move === 'in' ? 0 : 1); } else { return a.value - b.value; } }); // Simplify the breaks inBrk = 0; start = min; for (i in breakArrayT) { brk = breakArrayT[i]; inBrk += (brk.move === 'in' ? 1 : -1); if (inBrk === 1 && brk.move === 'in') { start = brk.value; } if (inBrk === 0) { breakArray.push({ from: start, to: brk.value, len: brk.value - start - (brk.size || 0) }); length += brk.value - start - (brk.size || 0); } } axis.breakArray = breakArray; fireEvent(axis, 'afterBreaks'); axis.transA *= ((max - axis.min) / (max - min - length)); axis.min = min; axis.max = max; }; } }); wrap(Series.prototype, 'generatePoints', function (proceed) { proceed.apply(this, stripArguments(arguments)); var series = this, xAxis = series.xAxis, yAxis = series.yAxis, points = series.points, point, i = points.length; if (xAxis && yAxis && (xAxis.options.breaks || yAxis.options.breaks)) { while (i--) { point = points[i]; if (xAxis.isInAnyBreak(point.x, true) || yAxis.isInAnyBreak(point.y, true)) { points.splice(i, 1); if (this.data[i]) { this.data[i].destroyElements(); // removes the graphics for this point if they exist } } } } }); wrap(H.seriesTypes.column.prototype, 'drawPoints', function (proceed) { proceed.apply(this); var series = this, points = series.points, yAxis = series.yAxis, breaks = yAxis.breakArray || [], point, brk, i, j, y; for (i = 0; i < points.length; i++) { point = points[i]; y = point.stackY || point.y; for (j = 0; j < breaks.length; j++) { brk = breaks[j]; if (y < brk.from) { break; } else if (y > brk.to) { fireEvent(yAxis, 'pointBreak', {point: point, brk: brk}); } else { fireEvent(yAxis, 'pointInBreak', {point: point, brk: brk}); } } } }); }(Highcharts)); /* **************************************************************************** * Start data grouping module * ******************************************************************************/ /*jslint white:true */ var DATA_GROUPING = 'dataGrouping', seriesProto = Series.prototype, tooltipProto = Tooltip.prototype, baseProcessData = seriesProto.processData, baseGeneratePoints = seriesProto.generatePoints, baseDestroy = seriesProto.destroy, baseTooltipFooterHeaderFormatter = tooltipProto.tooltipFooterHeaderFormatter, NUMBER = 'number', commonOptions = { approximation: 'average', // average, open, high, low, close, sum //enabled: null, // (true for stock charts, false for basic), //forced: undefined, groupPixelWidth: 2, // the first one is the point or start value, the second is the start value if we're dealing with range, // the third one is the end value if dealing with a range dateTimeLabelFormats: { millisecond: ['%A, %b %e, %H:%M:%S.%L', '%A, %b %e, %H:%M:%S.%L', '-%H:%M:%S.%L'], second: ['%A, %b %e, %H:%M:%S', '%A, %b %e, %H:%M:%S', '-%H:%M:%S'], minute: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'], hour: ['%A, %b %e, %H:%M', '%A, %b %e, %H:%M', '-%H:%M'], day: ['%A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'], week: ['Week from %A, %b %e, %Y', '%A, %b %e', '-%A, %b %e, %Y'], month: ['%B %Y', '%B', '-%B %Y'], year: ['%Y', '%Y', '-%Y'] } // smoothed = false, // enable this for navigator series only }, specificOptions = { // extends common options line: {}, spline: {}, area: {}, areaspline: {}, column: { approximation: 'sum', groupPixelWidth: 10 }, arearange: { approximation: 'range' }, areasplinerange: { approximation: 'range' }, columnrange: { approximation: 'range', groupPixelWidth: 10 }, candlestick: { approximation: 'ohlc', groupPixelWidth: 10 }, ohlc: { approximation: 'ohlc', groupPixelWidth: 5 } }, // units are defined in a separate array to allow complete overriding in case of a user option defaultDataGroupingUnits = [[ 'millisecond', // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ 'second', [1, 2, 5, 10, 15, 30] ], [ 'minute', [1, 2, 5, 10, 15, 30] ], [ 'hour', [1, 2, 3, 4, 6, 8, 12] ], [ 'day', [1] ], [ 'week', [1] ], [ 'month', [1, 3, 6] ], [ 'year', null ] ], /** * Define the available approximation types. The data grouping approximations takes an array * or numbers as the first parameter. In case of ohlc, four arrays are sent in as four parameters. * Each array consists only of numbers. In case null values belong to the group, the property * .hasNulls will be set to true on the array. */ approximations = { sum: function (arr) { var len = arr.length, ret; // 1. it consists of nulls exclusively if (!len && arr.hasNulls) { ret = null; // 2. it has a length and real values } else if (len) { ret = 0; while (len--) { ret += arr[len]; } } // 3. it has zero length, so just return undefined // => doNothing() return ret; }, average: function (arr) { var len = arr.length, ret = approximations.sum(arr); // If we have a number, return it divided by the length. If not, return // null or undefined based on what the sum method finds. if (typeof ret === NUMBER && len) { ret = ret / len; } return ret; }, open: function (arr) { return arr.length ? arr[0] : (arr.hasNulls ? null : UNDEFINED); }, high: function (arr) { return arr.length ? arrayMax(arr) : (arr.hasNulls ? null : UNDEFINED); }, low: function (arr) { return arr.length ? arrayMin(arr) : (arr.hasNulls ? null : UNDEFINED); }, close: function (arr) { return arr.length ? arr[arr.length - 1] : (arr.hasNulls ? null : UNDEFINED); }, // ohlc and range are special cases where a multidimensional array is input and an array is output ohlc: function (open, high, low, close) { open = approximations.open(open); high = approximations.high(high); low = approximations.low(low); close = approximations.close(close); if (typeof open === NUMBER || typeof high === NUMBER || typeof low === NUMBER || typeof close === NUMBER) { return [open, high, low, close]; } // else, return is undefined }, range: function (low, high) { low = approximations.low(low); high = approximations.high(high); if (typeof low === NUMBER || typeof high === NUMBER) { return [low, high]; } // else, return is undefined } }; /*jslint white:false */ /** * Takes parallel arrays of x and y data and groups the data into intervals defined by groupPositions, a collection * of starting x values for each group. */ seriesProto.groupData = function (xData, yData, groupPositions, approximation) { var series = this, data = series.data, dataOptions = series.options.data, groupedXData = [], groupedYData = [], dataLength = xData.length, pointX, pointY, groupedY, handleYData = !!yData, // when grouping the fake extended axis for panning, we don't need to consider y values = [[], [], [], []], approximationFn = typeof approximation === 'function' ? approximation : approximations[approximation], pointArrayMap = series.pointArrayMap, pointArrayMapLength = pointArrayMap && pointArrayMap.length, i; // Start with the first point within the X axis range (#2696) for (i = 0; i <= dataLength; i++) { if (xData[i] >= groupPositions[0]) { break; } } for (; i <= dataLength; i++) { // when a new group is entered, summarize and initiate the previous group while ((groupPositions[1] !== UNDEFINED && xData[i] >= groupPositions[1]) || i === dataLength) { // get the last group // get group x and y pointX = groupPositions.shift(); groupedY = approximationFn.apply(0, values); // push the grouped data if (groupedY !== UNDEFINED) { groupedXData.push(pointX); groupedYData.push(groupedY); } // reset the aggregate arrays values[0] = []; values[1] = []; values[2] = []; values[3] = []; // don't loop beyond the last group if (i === dataLength) { break; } } // break out if (i === dataLength) { break; } // for each raw data point, push it to an array that contains all values for this specific group if (pointArrayMap) { var index = series.cropStart + i, point = (data && data[index]) || series.pointClass.prototype.applyOptions.apply({ series: series }, [dataOptions[index]]), j, val; for (j = 0; j < pointArrayMapLength; j++) { val = point[pointArrayMap[j]]; if (typeof val === NUMBER) { values[j].push(val); } else if (val === null) { values[j].hasNulls = true; } } } else { pointY = handleYData ? yData[i] : null; if (typeof pointY === NUMBER) { values[0].push(pointY); } else if (pointY === null) { values[0].hasNulls = true; } } } return [groupedXData, groupedYData]; }; /** * Extend the basic processData method, that crops the data to the current zoom * range, with data grouping logic. */ seriesProto.processData = function () { var series = this, chart = series.chart, options = series.options, dataGroupingOptions = options[DATA_GROUPING], groupingEnabled = series.allowDG !== false && dataGroupingOptions && pick(dataGroupingOptions.enabled, chart.options._stock), hasGroupedData; // run base method series.forceCrop = groupingEnabled; // #334 series.groupPixelWidth = null; // #2110 series.hasProcessed = true; // #2692 // skip if processData returns false or if grouping is disabled (in that order) if (baseProcessData.apply(series, arguments) === false || !groupingEnabled) { return; } else { series.destroyGroupedData(); } var i, processedXData = series.processedXData, processedYData = series.processedYData, plotSizeX = chart.plotSizeX, xAxis = series.xAxis, ordinal = xAxis.options.ordinal, groupPixelWidth = series.groupPixelWidth = xAxis.getGroupPixelWidth && xAxis.getGroupPixelWidth(), nonGroupedPointRange = series.pointRange; // Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth if (groupPixelWidth) { hasGroupedData = true; series.points = null; // force recreation of point instances in series.translate var extremes = xAxis.getExtremes(), xMin = extremes.min, xMax = extremes.max, groupIntervalFactor = (ordinal && xAxis.getGroupIntervalFactor(xMin, xMax, series)) || 1, interval = (groupPixelWidth * (xMax - xMin) / plotSizeX) * groupIntervalFactor, groupPositions = xAxis.getTimeTicks( xAxis.normalizeTimeTickInterval(interval, dataGroupingOptions.units || defaultDataGroupingUnits), xMin, xMax, xAxis.options.startOfWeek, processedXData, series.closestPointRange ), groupedXandY = seriesProto.groupData.apply(series, [processedXData, processedYData, groupPositions, dataGroupingOptions.approximation]), groupedXData = groupedXandY[0], groupedYData = groupedXandY[1]; // prevent the smoothed data to spill out left and right, and make // sure data is not shifted to the left if (dataGroupingOptions.smoothed) { i = groupedXData.length - 1; groupedXData[i] = xMax; while (i-- && i > 0) { groupedXData[i] += interval / 2; } groupedXData[0] = xMin; } // record what data grouping values were used series.currentDataGrouping = groupPositions.info; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = groupPositions.info.totalRange; } series.closestPointRange = groupPositions.info.totalRange; // Make sure the X axis extends to show the first group (#2533) if (defined(groupedXData[0]) && groupedXData[0] < xAxis.dataMin) { if (xAxis.min === xAxis.dataMin) { xAxis.min = groupedXData[0]; } xAxis.dataMin = groupedXData[0]; } // set series props series.processedXData = groupedXData; series.processedYData = groupedYData; } else { series.currentDataGrouping = null; series.pointRange = nonGroupedPointRange; } series.hasGroupedData = hasGroupedData; }; /** * Destroy the grouped data points. #622, #740 */ seriesProto.destroyGroupedData = function () { var groupedData = this.groupedData; // clear previous groups each(groupedData || [], function (point, i) { if (point) { groupedData[i] = point.destroy ? point.destroy() : null; } }); this.groupedData = null; }; /** * Override the generatePoints method by adding a reference to grouped data */ seriesProto.generatePoints = function () { baseGeneratePoints.apply(this); // record grouped data in order to let it be destroyed the next time processData runs this.destroyGroupedData(); // #622 this.groupedData = this.hasGroupedData ? this.points : null; }; /** * Extend the original method, make the tooltip's header reflect the grouped range */ tooltipProto.tooltipFooterHeaderFormatter = function (point, isFooter) { var tooltip = this, series = point.series, options = series.options, tooltipOptions = series.tooltipOptions, dataGroupingOptions = options.dataGrouping, xDateFormat = tooltipOptions.xDateFormat, xDateFormatEnd, xAxis = series.xAxis, currentDataGrouping, dateTimeLabelFormats, labelFormats, formattedKey, ret; // apply only to grouped series if (xAxis && xAxis.options.type === 'datetime' && dataGroupingOptions && isNumber(point.key)) { // set variables currentDataGrouping = series.currentDataGrouping; dateTimeLabelFormats = dataGroupingOptions.dateTimeLabelFormats; // if we have grouped data, use the grouping information to get the right format if (currentDataGrouping) { labelFormats = dateTimeLabelFormats[currentDataGrouping.unitName]; if (currentDataGrouping.count === 1) { xDateFormat = labelFormats[0]; } else { xDateFormat = labelFormats[1]; xDateFormatEnd = labelFormats[2]; } // if not grouped, and we don't have set the xDateFormat option, get the best fit, // so if the least distance between points is one minute, show it, but if the // least distance is one day, skip hours and minutes etc. } else if (!xDateFormat && dateTimeLabelFormats) { xDateFormat = tooltip.getXDateFormat(point, tooltipOptions, xAxis); } // now format the key formattedKey = dateFormat(xDateFormat, point.key); if (xDateFormatEnd) { formattedKey += dateFormat(xDateFormatEnd, point.key + currentDataGrouping.totalRange - 1); } // return the replaced format ret = tooltipOptions[(isFooter ? 'footer' : 'header') + 'Format'].replace('{point.key}', formattedKey); // else, fall back to the regular formatter } else { ret = baseTooltipFooterHeaderFormatter.call(tooltip, point, isFooter); } return ret; }; /** * Extend the series destroyer */ seriesProto.destroy = function () { var series = this, groupedData = series.groupedData || [], i = groupedData.length; while (i--) { if (groupedData[i]) { groupedData[i].destroy(); } } baseDestroy.apply(series); }; // Handle default options for data grouping. This must be set at runtime because some series types are // defined after this. wrap(seriesProto, 'setOptions', function (proceed, itemOptions) { var options = proceed.call(this, itemOptions), type = this.type, plotOptions = this.chart.options.plotOptions, defaultOptions = defaultPlotOptions[type].dataGrouping; if (specificOptions[type]) { // #1284 if (!defaultOptions) { defaultOptions = merge(commonOptions, specificOptions[type]); } options.dataGrouping = merge( defaultOptions, plotOptions.series && plotOptions.series.dataGrouping, // #1228 plotOptions[type].dataGrouping, // Set by the StockChart constructor itemOptions.dataGrouping ); } if (this.chart.options._stock) { this.requireSorting = true; } return options; }); /** * When resetting the scale reset the hasProccessed flag to avoid taking previous data grouping * of neighbour series into accound when determining group pixel width (#2692). */ wrap(Axis.prototype, 'setScale', function (proceed) { proceed.call(this); each(this.series, function (series) { series.hasProcessed = false; }); }); /** * Get the data grouping pixel width based on the greatest defined individual width * of the axis' series, and if whether one of the axes need grouping. */ Axis.prototype.getGroupPixelWidth = function () { var series = this.series, len = series.length, i, groupPixelWidth = 0, doGrouping = false, dataLength, dgOptions; // If multiple series are compared on the same x axis, give them the same // group pixel width (#334) i = len; while (i--) { dgOptions = series[i].options.dataGrouping; if (dgOptions) { groupPixelWidth = mathMax(groupPixelWidth, dgOptions.groupPixelWidth); } } // If one of the series needs grouping, apply it to all (#1634) i = len; while (i--) { dgOptions = series[i].options.dataGrouping; if (dgOptions && series[i].hasProcessed) { // #2692 dataLength = (series[i].processedXData || series[i].data).length; // Execute grouping if the amount of points is greater than the limit defined in groupPixelWidth if (series[i].groupPixelWidth || dataLength > (this.chart.plotSizeX / groupPixelWidth) || (dataLength && dgOptions.forced)) { doGrouping = true; } } } return doGrouping ? groupPixelWidth : 0; }; /** * Force data grouping on all the axis' series. */ Axis.prototype.setDataGrouping = function (dataGrouping, redraw) { redraw = pick(redraw, true); if (!dataGrouping) { dataGrouping = { forced: false, units: null }; } // Axis is instantiated, update all series if (this instanceof Axis) { each(this.series, function (series) { series.update({ dataGrouping: dataGrouping }, false); }); // Axis not yet instanciated, alter series options } else { each(this.chart.options.series, function (seriesOptions) { seriesOptions.dataGrouping = dataGrouping; }); } }; /* **************************************************************************** * End data grouping module * ******************************************************************************//* **************************************************************************** * Start OHLC series code * *****************************************************************************/ // 1 - Set default options defaultPlotOptions.ohlc = merge(defaultPlotOptions.column, { lineWidth: 1, tooltip: { pointFormat: '<span style="color:{point.color}">\u25CF</span> <b> {series.name}</b><br/>' + // docs 'Open: {point.open}<br/>' + 'High: {point.high}<br/>' + 'Low: {point.low}<br/>' + 'Close: {point.close}<br/>' }, states: { hover: { lineWidth: 3 } }, threshold: null //upColor: undefined }); // 2 - Create the OHLCSeries object var OHLCSeries = extendClass(seriesTypes.column, { type: 'ohlc', pointArrayMap: ['open', 'high', 'low', 'close'], // array point configs are mapped to this toYData: function (point) { // return a plain array for speedy calculation return [point.open, point.high, point.low, point.close]; }, pointValKey: 'high', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'color', 'stroke-width': 'lineWidth' }, upColorProp: 'stroke', /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.column.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upColor = options.upColor || series.color, seriesDownPointAttr = merge(series.pointAttr), upColorProp = series.upColorProp; seriesDownPointAttr[''][upColorProp] = upColor; seriesDownPointAttr.hover[upColorProp] = stateOptions.hover.upColor || upColor; seriesDownPointAttr.select[upColorProp] = stateOptions.select.upColor || upColor; each(series.points, function (point) { if (point.open < point.close && !point.options.color) { point.pointAttr = seriesDownPointAttr; } }); }, /** * Translate data points from raw values x and y to plotX and plotY */ translate: function () { var series = this, yAxis = series.yAxis; seriesTypes.column.prototype.translate.apply(series); // do the translation each(series.points, function (point) { // the graphics if (point.open !== null) { point.plotOpen = yAxis.translate(point.open, 0, 1, 0, 1); } if (point.close !== null) { point.plotClose = yAxis.translate(point.close, 0, 1, 0, 1); } }); }, /** * Draw the data points */ drawPoints: function () { var series = this, points = series.points, chart = series.chart, pointAttr, plotOpen, plotClose, crispCorr, halfWidth, path, graphic, crispX; each(points, function (point) { if (point.plotY !== UNDEFINED) { graphic = point.graphic; pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || series.pointAttr[NORMAL_STATE]; // crisp vector coordinates crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathRound(point.plotX) - crispCorr; // #2596 halfWidth = mathRound(point.shapeArgs.width / 2); // the vertical stem path = [ 'M', crispX, mathRound(point.yBottom), 'L', crispX, mathRound(point.plotY) ]; // open if (point.open !== null) { plotOpen = mathRound(point.plotOpen) + crispCorr; path.push( 'M', crispX, plotOpen, 'L', crispX - halfWidth, plotOpen ); } // close if (point.close !== null) { plotClose = mathRound(point.plotClose) + crispCorr; path.push( 'M', crispX, plotClose, 'L', crispX + halfWidth, plotClose ); } // create and/or update the graphic if (graphic) { graphic .attr(pointAttr) // #3897 .animate({ d: path }); } else { point.graphic = chart.renderer.path(path) .attr(pointAttr) .add(series.group); } } }); }, /** * Disable animation */ animate: null }); seriesTypes.ohlc = OHLCSeries; /* **************************************************************************** * End OHLC series code * *****************************************************************************/ /* **************************************************************************** * Start Candlestick series code * *****************************************************************************/ // 1 - set default options defaultPlotOptions.candlestick = merge(defaultPlotOptions.column, { lineColor: 'black', lineWidth: 1, states: { hover: { lineWidth: 2 } }, tooltip: defaultPlotOptions.ohlc.tooltip, threshold: null, upColor: 'white' // upLineColor: null }); // 2 - Create the CandlestickSeries object var CandlestickSeries = extendClass(OHLCSeries, { type: 'candlestick', /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'color', stroke: 'lineColor', 'stroke-width': 'lineWidth' }, upColorProp: 'fill', /** * Postprocess mapping between options and SVG attributes */ getAttribs: function () { seriesTypes.ohlc.prototype.getAttribs.apply(this, arguments); var series = this, options = series.options, stateOptions = options.states, upLineColor = options.upLineColor || options.lineColor, hoverStroke = stateOptions.hover.upLineColor || upLineColor, selectStroke = stateOptions.select.upLineColor || upLineColor; // Add custom line color for points going up (close > open). // Fill is handled by OHLCSeries' getAttribs. each(series.points, function (point) { if (point.open < point.close) { point.pointAttr[''].stroke = upLineColor; point.pointAttr.hover.stroke = hoverStroke; point.pointAttr.select.stroke = selectStroke; } }); }, /** * Draw the data points */ drawPoints: function () { var series = this, //state = series.state, points = series.points, chart = series.chart, pointAttr, seriesPointAttr = series.pointAttr[''], plotOpen, plotClose, topBox, bottomBox, hasTopWhisker, hasBottomWhisker, crispCorr, crispX, graphic, path, halfWidth; each(points, function (point) { graphic = point.graphic; if (point.plotY !== UNDEFINED) { pointAttr = point.pointAttr[point.selected ? 'selected' : ''] || seriesPointAttr; // crisp vector coordinates crispCorr = (pointAttr['stroke-width'] % 2) / 2; crispX = mathRound(point.plotX) - crispCorr; // #2596 plotOpen = point.plotOpen; plotClose = point.plotClose; topBox = math.min(plotOpen, plotClose); bottomBox = math.max(plotOpen, plotClose); halfWidth = mathRound(point.shapeArgs.width / 2); hasTopWhisker = mathRound(topBox) !== mathRound(point.plotY); hasBottomWhisker = bottomBox !== point.yBottom; topBox = mathRound(topBox) + crispCorr; bottomBox = mathRound(bottomBox) + crispCorr; // create the path path = [ 'M', crispX - halfWidth, bottomBox, 'L', crispX - halfWidth, topBox, 'L', crispX + halfWidth, topBox, 'L', crispX + halfWidth, bottomBox, 'Z', // Use a close statement to ensure a nice rectangle #2602 'M', crispX, topBox, 'L', crispX, hasTopWhisker ? mathRound(point.plotY) : topBox, // #460, #2094 'M', crispX, bottomBox, 'L', crispX, hasBottomWhisker ? mathRound(point.yBottom) : bottomBox // #460, #2094 ]; if (graphic) { graphic .attr(pointAttr) // #3897 .animate({ d: path }); } else { point.graphic = chart.renderer.path(path) .attr(pointAttr) .add(series.group) .shadow(series.options.shadow); } } }); } }); seriesTypes.candlestick = CandlestickSeries; /* **************************************************************************** * End Candlestick series code * *****************************************************************************/ /* **************************************************************************** * Start Flags series code * *****************************************************************************/ var symbols = SVGRenderer.prototype.symbols; // 1 - set default options defaultPlotOptions.flags = merge(defaultPlotOptions.column, { fillColor: 'white', lineWidth: 1, pointRange: 0, // #673 //radius: 2, shape: 'flag', stackDistance: 12, states: { hover: { lineColor: 'black', fillColor: '#FCFFC5' } }, style: { fontSize: '11px', fontWeight: 'bold', textAlign: 'center' }, tooltip: { pointFormat: '{point.text}<br/>' }, threshold: null, y: -30 }); // 2 - Create the CandlestickSeries object seriesTypes.flags = extendClass(seriesTypes.column, { type: 'flags', sorted: false, noSharedTooltip: true, allowDG: false, takeOrdinalPosition: false, // #1074 trackerGroups: ['markerGroup'], forceCrop: true, /** * Inherit the initialization from base Series */ init: Series.prototype.init, /** * One-to-one mapping from options to SVG attributes */ pointAttrToOptions: { // mapping between SVG attributes and the corresponding options fill: 'fillColor', stroke: 'color', 'stroke-width': 'lineWidth', r: 'radius' }, /** * Extend the translate method by placing the point on the related series */ translate: function () { seriesTypes.column.prototype.translate.apply(this); var series = this, options = series.options, chart = series.chart, points = series.points, cursor = points.length - 1, point, lastPoint, optionsOnSeries = options.onSeries, onSeries = optionsOnSeries && chart.get(optionsOnSeries), step = onSeries && onSeries.options.step, onData = onSeries && onSeries.points, i = onData && onData.length, xAxis = series.xAxis, xAxisExt = xAxis.getExtremes(), leftPoint, lastX, rightPoint, currentDataGrouping; // relate to a master series if (onSeries && onSeries.visible && i) { currentDataGrouping = onSeries.currentDataGrouping; lastX = onData[i - 1].x + (currentDataGrouping ? currentDataGrouping.totalRange : 0); // #2374 // sort the data points points.sort(function (a, b) { return (a.x - b.x); }); while (i-- && points[cursor]) { point = points[cursor]; leftPoint = onData[i]; if (leftPoint.x <= point.x && leftPoint.plotY !== UNDEFINED) { if (point.x <= lastX) { // #803 point.plotY = leftPoint.plotY; // interpolate between points, #666 if (leftPoint.x < point.x && !step) { rightPoint = onData[i + 1]; if (rightPoint && rightPoint.plotY !== UNDEFINED) { point.plotY += ((point.x - leftPoint.x) / (rightPoint.x - leftPoint.x)) * // the distance ratio, between 0 and 1 (rightPoint.plotY - leftPoint.plotY); // the y distance } } } cursor--; i++; // check again for points in the same x position if (cursor < 0) { break; } } } } // Add plotY position and handle stacking each(points, function (point, i) { var stackIndex; // Undefined plotY means the point is either on axis, outside series range or hidden series. // If the series is outside the range of the x axis it should fall through with // an undefined plotY, but then we must remove the shapeArgs (#847). if (point.plotY === UNDEFINED) { if (point.x >= xAxisExt.min && point.x <= xAxisExt.max) { // we're inside xAxis range point.plotY = chart.chartHeight - xAxis.bottom - (xAxis.opposite ? xAxis.height : 0) + xAxis.offset - chart.plotTop; } else { point.shapeArgs = {}; // 847 } } // if multiple flags appear at the same x, order them into a stack lastPoint = points[i - 1]; if (lastPoint && lastPoint.plotX === point.plotX) { if (lastPoint.stackIndex === UNDEFINED) { lastPoint.stackIndex = 0; } stackIndex = lastPoint.stackIndex + 1; } point.stackIndex = stackIndex; // #3639 }); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, seriesPointAttr = series.pointAttr[''], points = series.points, chart = series.chart, renderer = chart.renderer, plotX, plotY, options = series.options, optionsY = options.y, shape, i, point, graphic, stackIndex, anchorX, anchorY, outsideRight; i = points.length; while (i--) { point = points[i]; outsideRight = point.plotX > series.xAxis.len; plotX = point.plotX - 1; stackIndex = point.stackIndex; shape = point.options.shape || options.shape; plotY = point.plotY; if (plotY !== UNDEFINED) { plotY = point.plotY + optionsY - (stackIndex !== UNDEFINED && stackIndex * options.stackDistance); } anchorX = stackIndex ? UNDEFINED : point.plotX; // skip connectors for higher level stacked points anchorY = stackIndex ? UNDEFINED : point.plotY; graphic = point.graphic; // only draw the point if y is defined and the flag is within the visible area if (plotY !== UNDEFINED && plotX >= 0 && !outsideRight) { // shortcuts pointAttr = point.pointAttr[point.selected ? 'select' : ''] || seriesPointAttr; if (graphic) { // update graphic.attr({ x: plotX, y: plotY, r: pointAttr.r, anchorX: anchorX, anchorY: anchorY }); } else { graphic = point.graphic = renderer.label( point.options.title || options.title || 'A', plotX, plotY, shape, anchorX, anchorY, options.useHTML ) .css(merge(options.style, point.style)) .attr(pointAttr) .attr({ align: shape === 'flag' ? 'left' : 'center', width: options.width, height: options.height }) .add(series.markerGroup) .shadow(options.shadow); } // Set the tooltip anchor position point.tooltipPos = [plotX, plotY]; } else if (graphic) { point.graphic = graphic.destroy(); } } }, /** * Extend the column trackers with listeners to expand and contract stacks */ drawTracker: function () { var series = this, points = series.points; TrackerMixin.drawTrackerPoint.apply(this); // Bring each stacked flag up on mouse over, this allows readability of vertically // stacked elements as well as tight points on the x axis. #1924. each(points, function (point) { var graphic = point.graphic; if (graphic) { addEvent(graphic.element, 'mouseover', function () { // Raise this point if (point.stackIndex > 0 && !point.raised) { point._y = graphic.y; graphic.attr({ y: point._y - 8 }); point.raised = true; } // Revert other raised points each(points, function (otherPoint) { if (otherPoint !== point && otherPoint.raised && otherPoint.graphic) { otherPoint.graphic.attr({ y: otherPoint._y }); otherPoint.raised = false; } }); }); } }); }, /** * Disable animation */ animate: noop, buildKDTree: noop, setClip: noop }); // create the flag icon with anchor symbols.flag = function (x, y, w, h, options) { var anchorX = (options && options.anchorX) || x, anchorY = (options && options.anchorY) || y; return [ 'M', anchorX, anchorY, 'L', x, y + h, x, y, x + w, y, x + w, y + h, x, y + h, 'M', anchorX, anchorY, 'Z' ]; }; // create the circlepin and squarepin icons with anchor each(['circle', 'square'], function (shape) { symbols[shape + 'pin'] = function (x, y, w, h, options) { var anchorX = options && options.anchorX, anchorY = options && options.anchorY, path, labelTopOrBottomY; // For single-letter flags, make sure circular flags are not taller than their width if (shape === 'circle' && h > w) { x -= mathRound((h - w) / 2); w = h; } path = symbols[shape](x, y, w, h); if (anchorX && anchorY) { // if the label is below the anchor, draw the connecting line from the top edge of the label // otherwise start drawing from the bottom edge labelTopOrBottomY = (y > anchorY) ? y : y + h; path.push('M', anchorX, labelTopOrBottomY, 'L', anchorX, anchorY); } return path; }; }); // The symbol callbacks are generated on the SVGRenderer object in all browsers. Even // VML browsers need this in order to generate shapes in export. Now share // them with the VMLRenderer. if (Renderer === Highcharts.VMLRenderer) { each(['flag', 'circlepin', 'squarepin'], function (shape) { VMLRenderer.prototype.symbols[shape] = symbols[shape]; }); } /* **************************************************************************** * End Flags series code * *****************************************************************************/ /* **************************************************************************** * Start Scroller code * *****************************************************************************/ var units = [].concat(defaultDataGroupingUnits), // copy defaultSeriesType, // Finding the min or max of a set of variables where we don't know if they are defined, // is a pattern that is repeated several places in Highcharts. Consider making this // a global utility method. numExt = function (extreme) { var numbers = grep(arguments, function (n) { return typeof n === 'number'; }); if (numbers.length) { return Math[extreme].apply(0, numbers); } }; // add more resolution to units units[4] = ['day', [1, 2, 3, 4]]; // allow more days units[5] = ['week', [1, 2, 3]]; // allow more weeks defaultSeriesType = seriesTypes.areaspline === UNDEFINED ? 'line' : 'areaspline'; extend(defaultOptions, { navigator: { //enabled: true, handles: { backgroundColor: '#ebe7e8', borderColor: '#b2b1b6' }, height: 40, margin: 25, maskFill: 'rgba(128,179,236,0.3)', maskInside: true, outlineColor: '#b2b1b6', outlineWidth: 1, series: { type: defaultSeriesType, color: '#4572A7', compare: null, fillOpacity: 0.05, dataGrouping: { approximation: 'average', enabled: true, groupPixelWidth: 2, smoothed: true, units: units }, dataLabels: { enabled: false, zIndex: 2 // #1839 }, id: PREFIX + 'navigator-series', lineColor: '#4572A7', lineWidth: 1, marker: { enabled: false }, pointRange: 0, shadow: false, threshold: null }, //top: undefined, xAxis: { tickWidth: 0, lineWidth: 0, gridLineColor: '#EEE', gridLineWidth: 1, tickPixelInterval: 200, labels: { align: 'left', style: { color: '#888' }, x: 3, y: -4 }, crosshair: false }, yAxis: { gridLineWidth: 0, startOnTick: false, endOnTick: false, minPadding: 0.1, maxPadding: 0.1, labels: { enabled: false }, crosshair: false, title: { text: null }, tickWidth: 0 } }, scrollbar: { //enabled: true height: isTouchDevice ? 20 : 14, barBackgroundColor: '#bfc8d1', barBorderRadius: 0, barBorderWidth: 1, barBorderColor: '#bfc8d1', buttonArrowColor: '#666', buttonBackgroundColor: '#ebe7e8', buttonBorderColor: '#bbb', buttonBorderRadius: 0, buttonBorderWidth: 1, minWidth: 6, rifleColor: '#666', trackBackgroundColor: '#eeeeee', trackBorderColor: '#eeeeee', trackBorderWidth: 1, // trackBorderRadius: 0 liveRedraw: hasSVG && !isTouchDevice } }); /** * The Scroller class * @param {Object} chart */ function Scroller(chart) { var chartOptions = chart.options, navigatorOptions = chartOptions.navigator, navigatorEnabled = navigatorOptions.enabled, scrollbarOptions = chartOptions.scrollbar, scrollbarEnabled = scrollbarOptions.enabled, height = navigatorEnabled ? navigatorOptions.height : 0, scrollbarHeight = scrollbarEnabled ? scrollbarOptions.height : 0; this.handles = []; this.scrollbarButtons = []; this.elementsToDestroy = []; // Array containing the elements to destroy when Scroller is destroyed this.chart = chart; this.setBaseSeries(); this.height = height; this.scrollbarHeight = scrollbarHeight; this.scrollbarEnabled = scrollbarEnabled; this.navigatorEnabled = navigatorEnabled; this.navigatorOptions = navigatorOptions; this.scrollbarOptions = scrollbarOptions; this.outlineHeight = height + scrollbarHeight; // Run scroller this.init(); } Scroller.prototype = { /** * Draw one of the handles on the side of the zoomed range in the navigator * @param {Number} x The x center for the handle * @param {Number} index 0 for left and 1 for right */ drawHandle: function (x, index) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, elementsToDestroy = scroller.elementsToDestroy, handles = scroller.handles, handlesOptions = scroller.navigatorOptions.handles, attr = { fill: handlesOptions.backgroundColor, stroke: handlesOptions.borderColor, 'stroke-width': 1 }, tempElem; // create the elements if (!scroller.rendered) { // the group handles[index] = renderer.g('navigator-handle-' + ['left', 'right'][index]) .css({ cursor: 'ew-resize' }) .attr({ zIndex: 4 - index }) // zIndex = 3 for right handle, 4 for left .add(); // the rectangle tempElem = renderer.rect(-4.5, 0, 9, 16, 0, 1) .attr(attr) .add(handles[index]); elementsToDestroy.push(tempElem); // the rifles tempElem = renderer.path([ 'M', -1.5, 4, 'L', -1.5, 12, 'M', 0.5, 4, 'L', 0.5, 12 ]).attr(attr) .add(handles[index]); elementsToDestroy.push(tempElem); } // Place it handles[index][chart.isResizing ? 'animate' : 'attr']({ translateX: scroller.scrollerLeft + scroller.scrollbarHeight + parseInt(x, 10), translateY: scroller.top + scroller.height / 2 - 8 }); }, /** * Draw the scrollbar buttons with arrows * @param {Number} index 0 is left, 1 is right */ drawScrollbarButton: function (index) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, elementsToDestroy = scroller.elementsToDestroy, scrollbarButtons = scroller.scrollbarButtons, scrollbarHeight = scroller.scrollbarHeight, scrollbarOptions = scroller.scrollbarOptions, tempElem; if (!scroller.rendered) { scrollbarButtons[index] = renderer.g().add(scroller.scrollbarGroup); tempElem = renderer.rect( -0.5, -0.5, scrollbarHeight + 1, // +1 to compensate for crispifying in rect method scrollbarHeight + 1, scrollbarOptions.buttonBorderRadius, scrollbarOptions.buttonBorderWidth ).attr({ stroke: scrollbarOptions.buttonBorderColor, 'stroke-width': scrollbarOptions.buttonBorderWidth, fill: scrollbarOptions.buttonBackgroundColor }).add(scrollbarButtons[index]); elementsToDestroy.push(tempElem); tempElem = renderer.path([ 'M', scrollbarHeight / 2 + (index ? -1 : 1), scrollbarHeight / 2 - 3, 'L', scrollbarHeight / 2 + (index ? -1 : 1), scrollbarHeight / 2 + 3, scrollbarHeight / 2 + (index ? 2 : -2), scrollbarHeight / 2 ]).attr({ fill: scrollbarOptions.buttonArrowColor }).add(scrollbarButtons[index]); elementsToDestroy.push(tempElem); } // adjust the right side button to the varying length of the scroll track if (index) { scrollbarButtons[index].attr({ translateX: scroller.scrollerWidth - scrollbarHeight }); } }, /** * Render the navigator and scroll bar * @param {Number} min X axis value minimum * @param {Number} max X axis value maximum * @param {Number} pxMin Pixel value minimum * @param {Number} pxMax Pixel value maximum */ render: function (min, max, pxMin, pxMax) { var scroller = this, chart = scroller.chart, renderer = chart.renderer, navigatorLeft, navigatorWidth, scrollerLeft, scrollerWidth, scrollbarGroup = scroller.scrollbarGroup, navigatorGroup = scroller.navigatorGroup, scrollbar = scroller.scrollbar, xAxis = scroller.xAxis, scrollbarTrack = scroller.scrollbarTrack, scrollbarHeight = scroller.scrollbarHeight, scrollbarEnabled = scroller.scrollbarEnabled, navigatorOptions = scroller.navigatorOptions, scrollbarOptions = scroller.scrollbarOptions, scrollbarMinWidth = scrollbarOptions.minWidth, height = scroller.height, top = scroller.top, navigatorEnabled = scroller.navigatorEnabled, outlineWidth = navigatorOptions.outlineWidth, halfOutline = outlineWidth / 2, zoomedMin, zoomedMax, range, scrX, scrWidth, scrollbarPad = 0, outlineHeight = scroller.outlineHeight, barBorderRadius = scrollbarOptions.barBorderRadius, strokeWidth, scrollbarStrokeWidth = scrollbarOptions.barBorderWidth, centerBarX, outlineTop = top + halfOutline, verb, unionExtremes; // Don't render the navigator until we have data (#486, #4202) if (!defined(min) || isNaN(min)) { return; } scroller.navigatorLeft = navigatorLeft = pick( xAxis.left, chart.plotLeft + scrollbarHeight // in case of scrollbar only, without navigator ); scroller.navigatorWidth = navigatorWidth = pick(xAxis.len, chart.plotWidth - 2 * scrollbarHeight); scroller.scrollerLeft = scrollerLeft = navigatorLeft - scrollbarHeight; scroller.scrollerWidth = scrollerWidth = scrollerWidth = navigatorWidth + 2 * scrollbarHeight; // Set the scroller x axis extremes to reflect the total. The navigator extremes // should always be the extremes of the union of all series in the chart as // well as the navigator series. if (xAxis.getExtremes) { unionExtremes = scroller.getUnionExtremes(true); if (unionExtremes && (unionExtremes.dataMin !== xAxis.min || unionExtremes.dataMax !== xAxis.max)) { xAxis.setExtremes(unionExtremes.dataMin, unionExtremes.dataMax, true, false); } } // Get the pixel position of the handles pxMin = pick(pxMin, xAxis.translate(min)); pxMax = pick(pxMax, xAxis.translate(max)); if (isNaN(pxMin) || mathAbs(pxMin) === Infinity) { // Verify (#1851, #2238) pxMin = 0; pxMax = scrollerWidth; } // Are we below the minRange? (#2618) if (xAxis.translate(pxMax, true) - xAxis.translate(pxMin, true) < chart.xAxis[0].minRange) { return; } // handles are allowed to cross, but never exceed the plot area scroller.zoomedMax = mathMin(mathMax(pxMin, pxMax), navigatorWidth); scroller.zoomedMin = mathMax(scroller.fixedWidth ? scroller.zoomedMax - scroller.fixedWidth : mathMin(pxMin, pxMax), 0); scroller.range = scroller.zoomedMax - scroller.zoomedMin; zoomedMax = mathRound(scroller.zoomedMax); zoomedMin = mathRound(scroller.zoomedMin); range = zoomedMax - zoomedMin; // on first render, create all elements if (!scroller.rendered) { if (navigatorEnabled) { // draw the navigator group scroller.navigatorGroup = navigatorGroup = renderer.g('navigator') .attr({ zIndex: 3 }) .add(); scroller.leftShade = renderer.rect() .attr({ fill: navigatorOptions.maskFill }).add(navigatorGroup); if (navigatorOptions.maskInside) { scroller.leftShade.css({ cursor: 'ew-resize '}); } else { scroller.rightShade = renderer.rect() .attr({ fill: navigatorOptions.maskFill }).add(navigatorGroup); } scroller.outline = renderer.path() .attr({ 'stroke-width': outlineWidth, stroke: navigatorOptions.outlineColor }) .add(navigatorGroup); } if (scrollbarEnabled) { // draw the scrollbar group scroller.scrollbarGroup = scrollbarGroup = renderer.g('scrollbar').add(); // the scrollbar track strokeWidth = scrollbarOptions.trackBorderWidth; scroller.scrollbarTrack = scrollbarTrack = renderer.rect().attr({ x: 0, y: -strokeWidth % 2 / 2, fill: scrollbarOptions.trackBackgroundColor, stroke: scrollbarOptions.trackBorderColor, 'stroke-width': strokeWidth, r: scrollbarOptions.trackBorderRadius || 0, height: scrollbarHeight }).add(scrollbarGroup); // the scrollbar itself scroller.scrollbar = scrollbar = renderer.rect() .attr({ y: -scrollbarStrokeWidth % 2 / 2, height: scrollbarHeight, fill: scrollbarOptions.barBackgroundColor, stroke: scrollbarOptions.barBorderColor, 'stroke-width': scrollbarStrokeWidth, r: barBorderRadius }) .add(scrollbarGroup); scroller.scrollbarRifles = renderer.path() .attr({ stroke: scrollbarOptions.rifleColor, 'stroke-width': 1 }) .add(scrollbarGroup); } } // place elements verb = chart.isResizing ? 'animate' : 'attr'; if (navigatorEnabled) { scroller.leftShade[verb](navigatorOptions.maskInside ? { x: navigatorLeft + zoomedMin, y: top, width: zoomedMax - zoomedMin, height: height } : { x: navigatorLeft, y: top, width: zoomedMin, height: height }); if (scroller.rightShade) { scroller.rightShade[verb]({ x: navigatorLeft + zoomedMax, y: top, width: navigatorWidth - zoomedMax, height: height }); } scroller.outline[verb]({ d: [ M, scrollerLeft, outlineTop, // left L, navigatorLeft + zoomedMin - halfOutline, outlineTop, // upper left of zoomed range navigatorLeft + zoomedMin - halfOutline, outlineTop + outlineHeight, // lower left of z.r. L, navigatorLeft + zoomedMax - halfOutline, outlineTop + outlineHeight, // lower right of z.r. L, navigatorLeft + zoomedMax - halfOutline, outlineTop, // upper right of z.r. scrollerLeft + scrollerWidth, outlineTop // right ].concat(navigatorOptions.maskInside ? [ M, navigatorLeft + zoomedMin + halfOutline, outlineTop, // upper left of zoomed range L, navigatorLeft + zoomedMax - halfOutline, outlineTop // upper right of z.r. ] : [])}); // draw handles scroller.drawHandle(zoomedMin + halfOutline, 0); scroller.drawHandle(zoomedMax + halfOutline, 1); } // draw the scrollbar if (scrollbarEnabled && scrollbarGroup) { // draw the buttons scroller.drawScrollbarButton(0); scroller.drawScrollbarButton(1); scrollbarGroup[verb]({ translateX: scrollerLeft, translateY: mathRound(outlineTop + height) }); scrollbarTrack[verb]({ width: scrollerWidth }); // prevent the scrollbar from drawing to small (#1246) scrX = scrollbarHeight + zoomedMin; scrWidth = range - scrollbarStrokeWidth; if (scrWidth < scrollbarMinWidth) { scrollbarPad = (scrollbarMinWidth - scrWidth) / 2; scrWidth = scrollbarMinWidth; scrX -= scrollbarPad; } scroller.scrollbarPad = scrollbarPad; scrollbar[verb]({ x: mathFloor(scrX) + (scrollbarStrokeWidth % 2 / 2), width: scrWidth }); centerBarX = scrollbarHeight + zoomedMin + range / 2 - 0.5; scroller.scrollbarRifles .attr({ visibility: range > 12 ? VISIBLE : HIDDEN })[verb]({ d: [ M, centerBarX - 3, scrollbarHeight / 4, L, centerBarX - 3, 2 * scrollbarHeight / 3, M, centerBarX, scrollbarHeight / 4, L, centerBarX, 2 * scrollbarHeight / 3, M, centerBarX + 3, scrollbarHeight / 4, L, centerBarX + 3, 2 * scrollbarHeight / 3 ] }); } scroller.scrollbarPad = scrollbarPad; scroller.rendered = true; }, /** * Set up the mouse and touch events for the navigator and scrollbar */ addEvents: function () { var container = this.chart.container, mouseDownHandler = this.mouseDownHandler, mouseMoveHandler = this.mouseMoveHandler, mouseUpHandler = this.mouseUpHandler, _events; // Mouse events _events = [ [container, 'mousedown', mouseDownHandler], [container, 'mousemove', mouseMoveHandler], [document, 'mouseup', mouseUpHandler] ]; // Touch events if (hasTouch) { _events.push( [container, 'touchstart', mouseDownHandler], [container, 'touchmove', mouseMoveHandler], [document, 'touchend', mouseUpHandler] ); } // Add them all each(_events, function (args) { addEvent.apply(null, args); }); this._events = _events; }, /** * Removes the event handlers attached previously with addEvents. */ removeEvents: function () { each(this._events, function (args) { removeEvent.apply(null, args); }); this._events = UNDEFINED; if (this.navigatorEnabled && this.baseSeries) { removeEvent(this.baseSeries, 'updatedData', this.updatedDataHandler); } }, /** * Initiate the Scroller object */ init: function () { var scroller = this, chart = scroller.chart, xAxis, yAxis, scrollbarHeight = scroller.scrollbarHeight, navigatorOptions = scroller.navigatorOptions, height = scroller.height, top = scroller.top, dragOffset, hasDragged, baseSeries = scroller.baseSeries; /** * Event handler for the mouse down event. */ scroller.mouseDownHandler = function (e) { e = chart.pointer.normalize(e); var zoomedMin = scroller.zoomedMin, zoomedMax = scroller.zoomedMax, top = scroller.top, scrollbarHeight = scroller.scrollbarHeight, scrollerLeft = scroller.scrollerLeft, scrollerWidth = scroller.scrollerWidth, navigatorLeft = scroller.navigatorLeft, navigatorWidth = scroller.navigatorWidth, scrollbarPad = scroller.scrollbarPad, range = scroller.range, chartX = e.chartX, chartY = e.chartY, baseXAxis = chart.xAxis[0], fixedMax, ext, handleSensitivity = isTouchDevice ? 10 : 7, left, isOnNavigator; if (chartY > top && chartY < top + height + scrollbarHeight) { // we're vertically inside the navigator isOnNavigator = !scroller.scrollbarEnabled || chartY < top + height; // grab the left handle if (isOnNavigator && math.abs(chartX - zoomedMin - navigatorLeft) < handleSensitivity) { scroller.grabbedLeft = true; scroller.otherHandlePos = zoomedMax; scroller.fixedExtreme = baseXAxis.max; chart.fixedRange = null; // grab the right handle } else if (isOnNavigator && math.abs(chartX - zoomedMax - navigatorLeft) < handleSensitivity) { scroller.grabbedRight = true; scroller.otherHandlePos = zoomedMin; scroller.fixedExtreme = baseXAxis.min; chart.fixedRange = null; // grab the zoomed range } else if (chartX > navigatorLeft + zoomedMin - scrollbarPad && chartX < navigatorLeft + zoomedMax + scrollbarPad) { scroller.grabbedCenter = chartX; scroller.fixedWidth = range; dragOffset = chartX - zoomedMin; // shift the range by clicking on shaded areas, scrollbar track or scrollbar buttons } else if (chartX > scrollerLeft && chartX < scrollerLeft + scrollerWidth) { // Center around the clicked point if (isOnNavigator) { left = chartX - navigatorLeft - range / 2; // Click on scrollbar } else { // Click left scrollbar button if (chartX < navigatorLeft) { left = zoomedMin - range * 0.2; // Click right scrollbar button } else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) { left = zoomedMin + range * 0.2; // Click on scrollbar track, shift the scrollbar by one range } else { left = chartX < navigatorLeft + zoomedMin ? // on the left zoomedMin - range : zoomedMax; } } if (left < 0) { left = 0; } else if (left + range >= navigatorWidth) { left = navigatorWidth - range; fixedMax = scroller.getUnionExtremes().dataMax; // #2293, #3543 } if (left !== zoomedMin) { // it has actually moved scroller.fixedWidth = range; // #1370 ext = xAxis.toFixedRange(left, left + range, null, fixedMax); baseXAxis.setExtremes( ext.min, ext.max, true, false, { trigger: 'navigator' } ); } } } }; /** * Event handler for the mouse move event. */ scroller.mouseMoveHandler = function (e) { var scrollbarHeight = scroller.scrollbarHeight, navigatorLeft = scroller.navigatorLeft, navigatorWidth = scroller.navigatorWidth, scrollerLeft = scroller.scrollerLeft, scrollerWidth = scroller.scrollerWidth, range = scroller.range, chartX; // In iOS, a mousemove event with e.pageX === 0 is fired when holding the finger // down in the center of the scrollbar. This should be ignored. if (e.pageX !== 0) { e = chart.pointer.normalize(e); chartX = e.chartX; // validation for handle dragging if (chartX < navigatorLeft) { chartX = navigatorLeft; } else if (chartX > scrollerLeft + scrollerWidth - scrollbarHeight) { chartX = scrollerLeft + scrollerWidth - scrollbarHeight; } // drag left handle if (scroller.grabbedLeft) { hasDragged = true; scroller.render(0, 0, chartX - navigatorLeft, scroller.otherHandlePos); // drag right handle } else if (scroller.grabbedRight) { hasDragged = true; scroller.render(0, 0, scroller.otherHandlePos, chartX - navigatorLeft); // drag scrollbar or open area in navigator } else if (scroller.grabbedCenter) { hasDragged = true; if (chartX < dragOffset) { // outside left chartX = dragOffset; } else if (chartX > navigatorWidth + dragOffset - range) { // outside right chartX = navigatorWidth + dragOffset - range; } scroller.render(0, 0, chartX - dragOffset, chartX - dragOffset + range); } if (hasDragged && scroller.scrollbarOptions.liveRedraw) { setTimeout(function () { scroller.mouseUpHandler(e); }, 0); } } }; /** * Event handler for the mouse up event. */ scroller.mouseUpHandler = function (e) { var ext, fixedMin, fixedMax; if (hasDragged) { // When dragging one handle, make sure the other one doesn't change if (scroller.zoomedMin === scroller.otherHandlePos) { fixedMin = scroller.fixedExtreme; } else if (scroller.zoomedMax === scroller.otherHandlePos) { fixedMax = scroller.fixedExtreme; } ext = xAxis.toFixedRange(scroller.zoomedMin, scroller.zoomedMax, fixedMin, fixedMax); chart.xAxis[0].setExtremes( ext.min, ext.max, true, false, { trigger: 'navigator', triggerOp: 'navigator-drag', DOMEvent: e // #1838 } ); } if (e.type !== 'mousemove') { scroller.grabbedLeft = scroller.grabbedRight = scroller.grabbedCenter = scroller.fixedWidth = scroller.fixedExtreme = scroller.otherHandlePos = hasDragged = dragOffset = null; } }; var xAxisIndex = chart.xAxis.length, yAxisIndex = chart.yAxis.length; // make room below the chart chart.extraBottomMargin = scroller.outlineHeight + navigatorOptions.margin; if (scroller.navigatorEnabled) { // an x axis is required for scrollbar also scroller.xAxis = xAxis = new Axis(chart, merge({ // inherit base xAxis' break and ordinal options breaks: baseSeries && baseSeries.xAxis.options.breaks, ordinal: baseSeries && baseSeries.xAxis.options.ordinal }, navigatorOptions.xAxis, { id: 'navigator-x-axis', isX: true, type: 'datetime', index: xAxisIndex, height: height, offset: 0, offsetLeft: scrollbarHeight, offsetRight: -scrollbarHeight, keepOrdinalPadding: true, // #2436 startOnTick: false, endOnTick: false, minPadding: 0, maxPadding: 0, zoomEnabled: false })); scroller.yAxis = yAxis = new Axis(chart, merge(navigatorOptions.yAxis, { id: 'navigator-y-axis', alignTicks: false, height: height, offset: 0, index: yAxisIndex, zoomEnabled: false })); // If we have a base series, initialize the navigator series if (baseSeries || navigatorOptions.series.data) { scroller.addBaseSeries(); // If not, set up an event to listen for added series } else if (chart.series.length === 0) { wrap(chart, 'redraw', function (proceed, animation) { // We've got one, now add it as base and reset chart.redraw if (chart.series.length > 0 && !scroller.series) { scroller.setBaseSeries(); chart.redraw = proceed; // reset } proceed.call(chart, animation); }); } // in case of scrollbar only, fake an x axis to get translation } else { scroller.xAxis = xAxis = { translate: function (value, reverse) { var axis = chart.xAxis[0], ext = axis.getExtremes(), scrollTrackWidth = chart.plotWidth - 2 * scrollbarHeight, min = numExt('min', axis.options.min, ext.dataMin), valueRange = numExt('max', axis.options.max, ext.dataMax) - min; return reverse ? // from pixel to value (value * valueRange / scrollTrackWidth) + min : // from value to pixel scrollTrackWidth * (value - min) / valueRange; }, toFixedRange: Axis.prototype.toFixedRange }; } /** * For stock charts, extend the Chart.getMargins method so that we can set the final top position * of the navigator once the height of the chart, including the legend, is determined. #367. */ wrap(chart, 'getMargins', function (proceed) { var legend = this.legend, legendOptions = legend.options; proceed.apply(this, [].slice.call(arguments, 1)); // Compute the top position scroller.top = top = scroller.navigatorOptions.top || this.chartHeight - scroller.height - scroller.scrollbarHeight - this.spacing[2] - (legendOptions.verticalAlign === 'bottom' && legendOptions.enabled && !legendOptions.floating ? legend.legendHeight + pick(legendOptions.margin, 10) : 0); if (xAxis && yAxis) { // false if navigator is disabled (#904) xAxis.options.top = yAxis.options.top = top; xAxis.setAxisSize(); yAxis.setAxisSize(); } }); scroller.addEvents(); }, /** * Get the union data extremes of the chart - the outer data extremes of the base * X axis and the navigator axis. */ getUnionExtremes: function (returnFalseOnNoBaseSeries) { var baseAxis = this.chart.xAxis[0], navAxis = this.xAxis, navAxisOptions = navAxis.options, baseAxisOptions = baseAxis.options, ret; if (!returnFalseOnNoBaseSeries || baseAxis.dataMin !== null) { ret = { dataMin: pick( // #4053 navAxisOptions && navAxisOptions.min, numExt( 'min', baseAxisOptions.min, baseAxis.dataMin, navAxis.dataMin ) ), dataMax: pick( navAxisOptions && navAxisOptions.max, numExt( 'max', baseAxisOptions.max, baseAxis.dataMax, navAxis.dataMax ) ) }; } return ret; }, /** * Set the base series. With a bit of modification we should be able to make * this an API method to be called from the outside */ setBaseSeries: function (baseSeriesOption) { var chart = this.chart; baseSeriesOption = baseSeriesOption || chart.options.navigator.baseSeries; // If we're resetting, remove the existing series if (this.series) { this.series.remove(); } // Set the new base series this.baseSeries = chart.series[baseSeriesOption] || (typeof baseSeriesOption === 'string' && chart.get(baseSeriesOption)) || chart.series[0]; // When run after render, this.xAxis already exists if (this.xAxis) { this.addBaseSeries(); } }, addBaseSeries: function () { var baseSeries = this.baseSeries, baseOptions = baseSeries ? baseSeries.options : {}, baseData = baseOptions.data, mergedNavSeriesOptions, navigatorSeriesOptions = this.navigatorOptions.series, navigatorData; // remove it to prevent merging one by one navigatorData = navigatorSeriesOptions.data; this.hasNavigatorData = !!navigatorData; // Merge the series options mergedNavSeriesOptions = merge(baseOptions, navigatorSeriesOptions, { enableMouseTracking: false, group: 'nav', // for columns padXAxis: false, xAxis: 'navigator-x-axis', yAxis: 'navigator-y-axis', name: 'Navigator', showInLegend: false, isInternal: true, visible: true }); // set the data back mergedNavSeriesOptions.data = navigatorData || baseData; // add the series this.series = this.chart.initSeries(mergedNavSeriesOptions); // Respond to updated data in the base series. // Abort if lazy-loading data from the server. if (baseSeries && this.navigatorOptions.adaptToUpdatedData !== false) { addEvent(baseSeries, 'updatedData', this.updatedDataHandler); // Survive Series.update() baseSeries.userOptions.events = extend(baseSeries.userOptions.event, { updatedData: this.updatedDataHandler }); } }, updatedDataHandler: function () { var scroller = this.chart.scroller, baseSeries = scroller.baseSeries, baseXAxis = baseSeries.xAxis, baseExtremes = baseXAxis.getExtremes(), baseMin = baseExtremes.min, baseMax = baseExtremes.max, baseDataMin = baseExtremes.dataMin, baseDataMax = baseExtremes.dataMax, range = baseMax - baseMin, stickToMin, stickToMax, newMax, newMin, doRedraw, navigatorSeries = scroller.series, navXData = navigatorSeries.xData, hasSetExtremes = !!baseXAxis.setExtremes; // detect whether to move the range stickToMax = baseMax >= navXData[navXData.length - 1] - (this.closestPointRange || 0); // #570 stickToMin = baseMin <= baseDataMin; // set the navigator series data to the new data of the base series if (!scroller.hasNavigatorData) { navigatorSeries.options.pointStart = baseSeries.xData[0]; navigatorSeries.setData(baseSeries.options.data, false); doRedraw = true; } // if the zoomed range is already at the min, move it to the right as new data // comes in if (stickToMin) { newMin = baseDataMin; newMax = newMin + range; } // if the zoomed range is already at the max, move it to the right as new data // comes in if (stickToMax) { newMax = baseDataMax; if (!stickToMin) { // if stickToMin is true, the new min value is set above newMin = mathMax(newMax - range, navigatorSeries.xData[0]); } } // update the extremes if (hasSetExtremes && (stickToMin || stickToMax)) { if (!isNaN(newMin)) { baseXAxis.setExtremes(newMin, newMax, true, false, { trigger: 'updatedData' }); } // if it is not at any edge, just move the scroller window to reflect the new series data } else { if (doRedraw) { this.chart.redraw(false); } scroller.render( mathMax(baseMin, baseDataMin), mathMin(baseMax, baseDataMax) ); } }, /** * Destroys allocated elements. */ destroy: function () { var scroller = this; // Disconnect events added in addEvents scroller.removeEvents(); // Destroy properties each([scroller.xAxis, scroller.yAxis, scroller.leftShade, scroller.rightShade, scroller.outline, scroller.scrollbarTrack, scroller.scrollbarRifles, scroller.scrollbarGroup, scroller.scrollbar], function (prop) { if (prop && prop.destroy) { prop.destroy(); } }); scroller.xAxis = scroller.yAxis = scroller.leftShade = scroller.rightShade = scroller.outline = scroller.scrollbarTrack = scroller.scrollbarRifles = scroller.scrollbarGroup = scroller.scrollbar = null; // Destroy elements in collection each([scroller.scrollbarButtons, scroller.handles, scroller.elementsToDestroy], function (coll) { destroyObjectProperties(coll); }); } }; Highcharts.Scroller = Scroller; /** * For Stock charts, override selection zooming with some special features because * X axis zooming is already allowed by the Navigator and Range selector. */ wrap(Axis.prototype, 'zoom', function (proceed, newMin, newMax) { var chart = this.chart, chartOptions = chart.options, zoomType = chartOptions.chart.zoomType, previousZoom, navigator = chartOptions.navigator, rangeSelector = chartOptions.rangeSelector, ret; if (this.isXAxis && ((navigator && navigator.enabled) || (rangeSelector && rangeSelector.enabled))) { // For x only zooming, fool the chart.zoom method not to create the zoom button // because the property already exists if (zoomType === 'x') { chart.resetZoomButton = 'blocked'; // For y only zooming, ignore the X axis completely } else if (zoomType === 'y') { ret = false; // For xy zooming, record the state of the zoom before zoom selection, then when // the reset button is pressed, revert to this state } else if (zoomType === 'xy') { previousZoom = this.previousZoom; if (defined(newMin)) { this.previousZoom = [this.min, this.max]; } else if (previousZoom) { newMin = previousZoom[0]; newMax = previousZoom[1]; delete this.previousZoom; } } } return ret !== UNDEFINED ? ret : proceed.call(this, newMin, newMax); }); // Initialize scroller for stock charts wrap(Chart.prototype, 'init', function (proceed, options, callback) { addEvent(this, 'beforeRender', function () { var options = this.options; if (options.navigator.enabled || options.scrollbar.enabled) { this.scroller = new Scroller(this); } }); proceed.call(this, options, callback); }); // Pick up badly formatted point options to addPoint wrap(Series.prototype, 'addPoint', function (proceed, options, redraw, shift, animation) { var turboThreshold = this.options.turboThreshold; if (turboThreshold && this.xData.length > turboThreshold && isObject(options) && !isArray(options) && this.chart.scroller) { error(20, true); } proceed.call(this, options, redraw, shift, animation); }); /* **************************************************************************** * End Scroller code * *****************************************************************************/ /* **************************************************************************** * Start Range Selector code * *****************************************************************************/ extend(defaultOptions, { rangeSelector: { // allButtonsEnabled: false, // enabled: true, // buttons: {Object} // buttonSpacing: 0, buttonTheme: { width: 28, height: 18, fill: '#f7f7f7', padding: 2, r: 0, 'stroke-width': 0, style: { color: '#444', cursor: 'pointer', fontWeight: 'normal' }, zIndex: 7, // #484, #852 states: { hover: { fill: '#e7e7e7' }, select: { fill: '#e7f0f9', style: { color: 'black', fontWeight: 'bold' } } } }, inputPosition: { align: 'right' }, // inputDateFormat: '%b %e, %Y', // inputEditDateFormat: '%Y-%m-%d', // inputEnabled: true, // inputStyle: {}, labelStyle: { color: '#666' } // selected: undefined } }); defaultOptions.lang = merge(defaultOptions.lang, { rangeSelectorZoom: 'Zoom', rangeSelectorFrom: 'From', rangeSelectorTo: 'To' }); /** * The object constructor for the range selector * @param {Object} chart */ function RangeSelector(chart) { // Run RangeSelector this.init(chart); } RangeSelector.prototype = { /** * The method to run when one of the buttons in the range selectors is clicked * @param {Number} i The index of the button * @param {Object} rangeOptions * @param {Boolean} redraw */ clickButton: function (i, redraw) { var rangeSelector = this, selected = rangeSelector.selected, chart = rangeSelector.chart, buttons = rangeSelector.buttons, rangeOptions = rangeSelector.buttonOptions[i], baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis || {}, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, newMin, newMax = baseAxis && mathRound(mathMin(baseAxis.max, pick(dataMax, baseAxis.max))), // #1568 now, date = new Date(newMax), type = rangeOptions.type, count = rangeOptions.count, baseXAxisOptions, range = rangeOptions._range, rangeMin, year, timeName, dataGrouping = rangeOptions.dataGrouping; if (dataMin === null || dataMax === null || // chart has no data, base series is removed i === rangeSelector.selected) { // same button is clicked twice return; } // Apply dataGrouping associated to button if (dataGrouping) { this.forcedDataGrouping = true; Axis.prototype.setDataGrouping.call(baseAxis || { chart: this.chart }, dataGrouping, false); } // Apply range if (type === 'month' || type === 'year') { timeName = { month: 'Month', year: 'FullYear'}[type]; date['set' + timeName](date['get' + timeName]() - count); newMin = date.getTime(); dataMin = pick(dataMin, Number.MIN_VALUE); if (isNaN(newMin) || newMin < dataMin) { newMin = dataMin; newMax = mathMin(newMin + range, dataMax); } else { range = newMax - newMin; } // Fixed times like minutes, hours, days } else if (range) { newMin = mathMax(newMax - range, dataMin); newMax = mathMin(newMin + range, dataMax); } else if (type === 'ytd') { // On user clicks on the buttons, or a delayed action running from the beforeRender // event (below), the baseAxis is defined. if (baseAxis) { // When "ytd" is the pre-selected button for the initial view, its calculation // is delayed and rerun in the beforeRender event (below). When the series // are initialized, but before the chart is rendered, we have access to the xData // array (#942). if (dataMax === UNDEFINED) { dataMin = Number.MAX_VALUE; dataMax = Number.MIN_VALUE; each(chart.series, function (series) { var xData = series.xData; // reassign it to the last item dataMin = mathMin(xData[0], dataMin); dataMax = mathMax(xData[xData.length - 1], dataMax); }); redraw = false; } now = new Date(dataMax); year = now.getFullYear(); newMin = rangeMin = mathMax(dataMin || 0, Date.UTC(year, 0, 1)); now = now.getTime(); newMax = mathMin(dataMax || now, now); // "ytd" is pre-selected. We don't yet have access to processed point and extremes data // (things like pointStart and pointInterval are missing), so we delay the process (#942) } else { addEvent(chart, 'beforeRender', function () { rangeSelector.clickButton(i); }); return; } } else if (type === 'all' && baseAxis) { newMin = dataMin; newMax = dataMax; } // Deselect previous button if (buttons[selected]) { buttons[selected].setState(0); } // Select this button if (buttons[i]) { buttons[i].setState(2); } chart.fixedRange = range; // update the chart if (!baseAxis) { // axis not yet instanciated baseXAxisOptions = chart.options.xAxis; baseXAxisOptions[0] = merge( baseXAxisOptions[0], { range: range, min: rangeMin } ); rangeSelector.setSelected(i); } else { // existing axis object; after render time baseAxis.setExtremes( newMin, newMax, pick(redraw, 1), 0, { trigger: 'rangeSelectorButton', rangeSelectorButton: rangeOptions } ); rangeSelector.setSelected(i); } }, /** * Set the selected option. This method only sets the internal flag, it doesn't * update the buttons or the actual zoomed range. */ setSelected: function (selected) { this.selected = this.options.selected = selected; }, /** * The default buttons for pre-selecting time frames */ defaultButtons: [{ type: 'month', count: 1, text: '1m' }, { type: 'month', count: 3, text: '3m' }, { type: 'month', count: 6, text: '6m' }, { type: 'ytd', text: 'YTD' }, { type: 'year', count: 1, text: '1y' }, { type: 'all', text: 'All' }], /** * Initialize the range selector */ init: function (chart) { var rangeSelector = this, options = chart.options.rangeSelector, buttonOptions = options.buttons || [].concat(rangeSelector.defaultButtons), selectedOption = options.selected, blurInputs = rangeSelector.blurInputs = function () { var minInput = rangeSelector.minInput, maxInput = rangeSelector.maxInput; if (minInput && minInput.blur) { //#3274 in some case blur is not defined fireEvent(minInput, 'blur'); //#3274 } if (maxInput && maxInput.blur) { //#3274 in some case blur is not defined fireEvent(maxInput, 'blur'); //#3274 } }; rangeSelector.chart = chart; rangeSelector.options = options; rangeSelector.buttons = []; chart.extraTopMargin = 35; rangeSelector.buttonOptions = buttonOptions; addEvent(chart.container, 'mousedown', blurInputs); addEvent(chart, 'resize', blurInputs); // Extend the buttonOptions with actual range each(buttonOptions, rangeSelector.computeButtonRange); // zoomed range based on a pre-selected button index if (selectedOption !== UNDEFINED && buttonOptions[selectedOption]) { this.clickButton(selectedOption, false); } addEvent(chart, 'load', function () { // If a data grouping is applied to the current button, release it when extremes change addEvent(chart.xAxis[0], 'setExtremes', function (e) { if (this.max - this.min !== chart.fixedRange && e.trigger !== 'rangeSelectorButton' && e.trigger !== 'updatedData' && rangeSelector.forcedDataGrouping) { this.setDataGrouping(false, false); } }); // Normalize the pressed button whenever a new range is selected addEvent(chart.xAxis[0], 'afterSetExtremes', function () { rangeSelector.updateButtonStates(true); }); }); }, /** * Dynamically update the range selector buttons after a new range has been set */ updateButtonStates: function (updating) { var rangeSelector = this, chart = this.chart, baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, selected = rangeSelector.selected, allButtonsEnabled = rangeSelector.options.allButtonsEnabled, buttons = rangeSelector.buttons; if (updating && chart.fixedRange !== mathRound(baseAxis.max - baseAxis.min)) { if (buttons[selected]) { buttons[selected].setState(0); } rangeSelector.setSelected(null); } each(rangeSelector.buttonOptions, function (rangeOptions, i) { var range = rangeOptions._range, // Disable buttons where the range exceeds what is allowed in the current view isTooGreatRange = range > dataMax - dataMin, // Disable buttons where the range is smaller than the minimum range isTooSmallRange = range < baseAxis.minRange, // Disable the All button if we're already showing all isAllButAlreadyShowingAll = rangeOptions.type === 'all' && baseAxis.max - baseAxis.min >= dataMax - dataMin && buttons[i].state !== 2, // Disable the YTD button if the complete range is within the same year isYTDButNotAvailable = rangeOptions.type === 'ytd' && dateFormat('%Y', dataMin) === dateFormat('%Y', dataMax); // The new zoom area happens to match the range for a button - mark it selected. // This happens when scrolling across an ordinal gap. It can be seen in the intraday // demos when selecting 1h and scroll across the night gap. if (range === mathRound(baseAxis.max - baseAxis.min) && i !== selected) { rangeSelector.setSelected(i); buttons[i].setState(2); } else if (!allButtonsEnabled && (isTooGreatRange || isTooSmallRange || isAllButAlreadyShowingAll || isYTDButNotAvailable)) { buttons[i].setState(3); } else if (buttons[i].state === 3) { buttons[i].setState(0); } }); }, /** * Compute and cache the range for an individual button */ computeButtonRange: function (rangeOptions) { var type = rangeOptions.type, count = rangeOptions.count || 1, // these time intervals have a fixed number of milliseconds, as opposed // to month, ytd and year fixedTimes = { millisecond: 1, second: 1000, minute: 60 * 1000, hour: 3600 * 1000, day: 24 * 3600 * 1000, week: 7 * 24 * 3600 * 1000 }; // Store the range on the button object if (fixedTimes[type]) { rangeOptions._range = fixedTimes[type] * count; } else if (type === 'month' || type === 'year') { rangeOptions._range = { month: 30, year: 365 }[type] * 24 * 36e5 * count; } }, /** * Set the internal and displayed value of a HTML input for the dates * @param {String} name * @param {Number} time */ setInputValue: function (name, time) { var options = this.chart.options.rangeSelector; if (defined(time)) { this[name + 'Input'].HCTime = time; } this[name + 'Input'].value = dateFormat(options.inputEditDateFormat || '%Y-%m-%d', this[name + 'Input'].HCTime); this[name + 'DateBox'].attr({ text: dateFormat(options.inputDateFormat || '%b %e, %Y', this[name + 'Input'].HCTime) }); }, showInput: function (name) { var inputGroup = this.inputGroup, dateBox = this[name + 'DateBox']; css(this[name + 'Input'], { left: (inputGroup.translateX + dateBox.x) + PX, top: inputGroup.translateY + PX, width: (dateBox.width - 2) + PX, height: (dateBox.height - 2) + PX, border: '2px solid silver' }); }, hideInput: function (name) { if (document.activeElement === this[name + 'Input']) { // Prevent running again and again css(this[name + 'Input'], { border: 0, width: '1px', height: '1px' }); this.setInputValue(name); } }, /** * Draw either the 'from' or the 'to' HTML input box of the range selector * @param {Object} name */ drawInput: function (name) { var rangeSelector = this, chart = rangeSelector.chart, chartStyle = chart.renderer.style, renderer = chart.renderer, options = chart.options.rangeSelector, lang = defaultOptions.lang, div = rangeSelector.div, isMin = name === 'min', input, label, dateBox, inputGroup = this.inputGroup; // Create the text label this[name + 'Label'] = label = renderer.label(lang[isMin ? 'rangeSelectorFrom' : 'rangeSelectorTo'], this.inputGroup.offset) .attr({ padding: 2 }) .css(merge(chartStyle, options.labelStyle)) .add(inputGroup); inputGroup.offset += label.width + 5; // Create an SVG label that shows updated date ranges and and records click events that // bring in the HTML input. this[name + 'DateBox'] = dateBox = renderer.label('', inputGroup.offset) .attr({ padding: 2, width: options.inputBoxWidth || 90, height: options.inputBoxHeight || 17, stroke: options.inputBoxBorderColor || 'silver', 'stroke-width': 1 }) .css(merge({ textAlign: 'center', color: '#444' }, chartStyle, options.inputStyle)) .on('click', function () { rangeSelector.showInput(name); // If it is already focused, the onfocus event doesn't fire (#3713) rangeSelector[name + 'Input'].focus(); }) .add(inputGroup); inputGroup.offset += dateBox.width + (isMin ? 10 : 0); // Create the HTML input element. This is rendered as 1x1 pixel then set to the right size // when focused. this[name + 'Input'] = input = createElement('input', { name: name, className: PREFIX + 'range-selector', type: 'text' }, extend({ position: ABSOLUTE, border: 0, width: '1px', // Chrome needs a pixel to see it height: '1px', padding: 0, textAlign: 'center', fontSize: chartStyle.fontSize, fontFamily: chartStyle.fontFamily, top: chart.plotTop + PX // prevent jump on focus in Firefox }, options.inputStyle), div); // Blow up the input box input.onfocus = function () { rangeSelector.showInput(name); }; // Hide away the input box input.onblur = function () { rangeSelector.hideInput(name); }; // handle changes in the input boxes input.onchange = function () { var inputValue = input.value, value = (options.inputDateParser || Date.parse)(inputValue), xAxis = chart.xAxis[0], dataMin = xAxis.dataMin, dataMax = xAxis.dataMax; // If the value isn't parsed directly to a value by the browser's Date.parse method, // like YYYY-MM-DD in IE, try parsing it a different way if (isNaN(value)) { value = inputValue.split('-'); value = Date.UTC(pInt(value[0]), pInt(value[1]) - 1, pInt(value[2])); } if (!isNaN(value)) { // Correct for timezone offset (#433) if (!defaultOptions.global.useUTC) { value = value + new Date().getTimezoneOffset() * 60 * 1000; } // Validate the extremes. If it goes beyound the data min or max, use the // actual data extreme (#2438). if (isMin) { if (value > rangeSelector.maxInput.HCTime) { value = UNDEFINED; } else if (value < dataMin) { value = dataMin; } } else { if (value < rangeSelector.minInput.HCTime) { value = UNDEFINED; } else if (value > dataMax) { value = dataMax; } } // Set the extremes if (value !== UNDEFINED) { chart.xAxis[0].setExtremes( isMin ? value : xAxis.min, isMin ? xAxis.max : value, UNDEFINED, UNDEFINED, { trigger: 'rangeSelectorInput' } ); } } }; }, /** * Render the range selector including the buttons and the inputs. The first time render * is called, the elements are created and positioned. On subsequent calls, they are * moved and updated. * @param {Number} min X axis minimum * @param {Number} max X axis maximum */ render: function (min, max) { var rangeSelector = this, chart = rangeSelector.chart, renderer = chart.renderer, container = chart.container, chartOptions = chart.options, navButtonOptions = chartOptions.exporting && chartOptions.navigation && chartOptions.navigation.buttonOptions, options = chartOptions.rangeSelector, buttons = rangeSelector.buttons, lang = defaultOptions.lang, div = rangeSelector.div, inputGroup = rangeSelector.inputGroup, buttonTheme = options.buttonTheme, buttonPosition = options.buttonPosition || {}, inputEnabled = options.inputEnabled, states = buttonTheme && buttonTheme.states, plotLeft = chart.plotLeft, yAlign, buttonLeft, buttonTop, buttonGroup = rangeSelector.group, buttonBBox; // create the elements if (!rangeSelector.rendered) { rangeSelector.group = buttonGroup = renderer.g('range-selector-buttons').add(); rangeSelector.zoomText = renderer.text(lang.rangeSelectorZoom, pick(buttonPosition.x, plotLeft), pick(buttonPosition.y, chart.plotTop - 35) + 15) .css(options.labelStyle) .add(buttonGroup); // button starting position buttonLeft = pick(buttonPosition.x, plotLeft) + rangeSelector.zoomText.getBBox().width + 5; buttonTop = pick(buttonPosition.y, chart.plotTop - 35); each(rangeSelector.buttonOptions, function (rangeOptions, i) { buttons[i] = renderer.button( rangeOptions.text, buttonLeft, buttonTop, function () { rangeSelector.clickButton(i); rangeSelector.isActive = true; }, buttonTheme, states && states.hover, states && states.select, states && states.disabled ) .css({ textAlign: 'center' }) .add(buttonGroup); // increase button position for the next button buttonLeft += buttons[i].width + pick(options.buttonSpacing, 5); if (rangeSelector.selected === i) { buttons[i].setState(2); } }); rangeSelector.updateButtonStates(); // first create a wrapper outside the container in order to make // the inputs work and make export correct if (inputEnabled !== false) { rangeSelector.div = div = createElement('div', null, { position: 'relative', height: 0, zIndex: 1 // above container }); container.parentNode.insertBefore(div, container); // Create the group to keep the inputs rangeSelector.inputGroup = inputGroup = renderer.g('input-group') .add(); inputGroup.offset = 0; rangeSelector.drawInput('min'); rangeSelector.drawInput('max'); } } if (inputEnabled !== false) { // Update the alignment to the updated spacing box yAlign = chart.plotTop - 45; inputGroup.align(extend({ y: yAlign, width: inputGroup.offset, // Detect collision with the exporting buttons x: navButtonOptions && (yAlign < (navButtonOptions.y || 0) + navButtonOptions.height - chart.spacing[0]) ? -40 : 0 }, options.inputPosition), true, chart.spacingBox); // Hide if overlapping - inputEnabled is null or undefined if (!defined(inputEnabled)) { buttonBBox = buttonGroup.getBBox(); inputGroup[inputGroup.translateX < buttonBBox.x + buttonBBox.width + 10 ? 'hide' : 'show'](); } // Set or reset the input values rangeSelector.setInputValue('min', min); rangeSelector.setInputValue('max', max); } rangeSelector.rendered = true; }, /** * Destroys allocated elements. */ destroy: function () { var minInput = this.minInput, maxInput = this.maxInput, chart = this.chart, blurInputs = this.blurInputs, key; removeEvent(chart.container, 'mousedown', blurInputs); removeEvent(chart, 'resize', blurInputs); // Destroy elements in collections destroyObjectProperties(this.buttons); // Clear input element events if (minInput) { minInput.onfocus = minInput.onblur = minInput.onchange = null; } if (maxInput) { maxInput.onfocus = maxInput.onblur = maxInput.onchange = null; } // Destroy HTML and SVG elements for (key in this) { if (this[key] && key !== 'chart') { if (this[key].destroy) { // SVGElement this[key].destroy(); } else if (this[key].nodeType) { // HTML element discardElement(this[key]); } } this[key] = null; } } }; /** * Add logic to normalize the zoomed range in order to preserve the pressed state of range selector buttons */ Axis.prototype.toFixedRange = function (pxMin, pxMax, fixedMin, fixedMax) { var fixedRange = this.chart && this.chart.fixedRange, newMin = pick(fixedMin, this.translate(pxMin, true)), newMax = pick(fixedMax, this.translate(pxMax, true)), changeRatio = fixedRange && (newMax - newMin) / fixedRange; // If the difference between the fixed range and the actual requested range is // too great, the user is dragging across an ordinal gap, and we need to release // the range selector button. if (changeRatio > 0.7 && changeRatio < 1.3) { if (fixedMax) { newMin = newMax - fixedRange; } else { newMax = newMin + fixedRange; } } return { min: newMin, max: newMax }; }; // Initialize scroller for stock charts wrap(Chart.prototype, 'init', function (proceed, options, callback) { addEvent(this, 'init', function () { if (this.options.rangeSelector.enabled) { this.rangeSelector = new RangeSelector(this); } }); proceed.call(this, options, callback); }); Highcharts.RangeSelector = RangeSelector; /* **************************************************************************** * End Range Selector code * *****************************************************************************/ Chart.prototype.callbacks.push(function (chart) { var extremes, scroller = chart.scroller, rangeSelector = chart.rangeSelector; function renderScroller() { extremes = chart.xAxis[0].getExtremes(); scroller.render(extremes.min, extremes.max); } function renderRangeSelector() { extremes = chart.xAxis[0].getExtremes(); if (!isNaN(extremes.min)) { rangeSelector.render(extremes.min, extremes.max); } } function afterSetExtremesHandlerScroller(e) { if (e.triggerOp !== 'navigator-drag') { scroller.render(e.min, e.max); } } function afterSetExtremesHandlerRangeSelector(e) { rangeSelector.render(e.min, e.max); } function destroyEvents() { if (scroller) { removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerScroller); } if (rangeSelector) { removeEvent(chart, 'resize', renderRangeSelector); removeEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector); } } // initiate the scroller if (scroller) { // redraw the scroller on setExtremes addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerScroller); // redraw the scroller on chart resize or box resize wrap(chart, 'drawChartBox', function (proceed) { var isDirtyBox = this.isDirtyBox; proceed.call(this); if (isDirtyBox) { renderScroller(); } }); // do it now renderScroller(); } if (rangeSelector) { // redraw the scroller on setExtremes addEvent(chart.xAxis[0], 'afterSetExtremes', afterSetExtremesHandlerRangeSelector); // redraw the scroller chart resize addEvent(chart, 'resize', renderRangeSelector); // do it now renderRangeSelector(); } // Remove resize/afterSetExtremes at chart destroy addEvent(chart, 'destroy', destroyEvents); }); /** * A wrapper for Chart with all the default values for a Stock chart */ Highcharts.StockChart = function (options, callback) { var seriesOptions = options.series, // to increase performance, don't merge the data opposite, // Always disable startOnTick:true on the main axis when the navigator is enabled (#1090) navigatorEnabled = pick(options.navigator && options.navigator.enabled, true), disableStartOnTick = navigatorEnabled ? { startOnTick: false, endOnTick: false } : null, lineOptions = { marker: { enabled: false, radius: 2 } // gapSize: 0 }, columnOptions = { shadow: false, borderWidth: 0 }; // apply X axis options to both single and multi y axes options.xAxis = map(splat(options.xAxis || {}), function (xAxisOptions) { return merge({ // defaults minPadding: 0, maxPadding: 0, ordinal: true, title: { text: null }, labels: { overflow: 'justify' }, showLastLabel: true }, xAxisOptions, // user options { // forced options type: 'datetime', categories: null }, disableStartOnTick ); }); // apply Y axis options to both single and multi y axes options.yAxis = map(splat(options.yAxis || {}), function (yAxisOptions) { opposite = pick(yAxisOptions.opposite, true); return merge({ // defaults labels: { y: -2 }, opposite: opposite, showLastLabel: false, title: { text: null } }, yAxisOptions // user options ); }); options.series = null; options = merge({ chart: { panning: true, pinchType: 'x' }, navigator: { enabled: true }, scrollbar: { enabled: true }, rangeSelector: { enabled: true }, title: { text: null, style: { fontSize: '16px' } }, tooltip: { shared: true, crosshairs: true }, legend: { enabled: false }, plotOptions: { line: lineOptions, spline: lineOptions, area: lineOptions, areaspline: lineOptions, arearange: lineOptions, areasplinerange: lineOptions, column: columnOptions, columnrange: columnOptions, candlestick: columnOptions, ohlc: columnOptions } }, options, // user's options { // forced options _stock: true, // internal flag chart: { inverted: false } }); options.series = seriesOptions; return new Chart(options, callback); }; // Implement the pinchType option wrap(Pointer.prototype, 'init', function (proceed, chart, options) { var pinchType = options.chart.pinchType || ''; proceed.call(this, chart, options); // Pinch status this.pinchX = this.pinchHor = pinchType.indexOf('x') !== -1; this.pinchY = this.pinchVert = pinchType.indexOf('y') !== -1; this.hasZoom = this.hasZoom || this.pinchHor || this.pinchVert; }); // Override the automatic label alignment so that the first Y axis' labels // are drawn on top of the grid line, and subsequent axes are drawn outside wrap(Axis.prototype, 'autoLabelAlign', function (proceed) { var chart = this.chart, options = this.options, panes = chart._labelPanes = chart._labelPanes || {}, key, labelOptions = this.options.labels; if (this.chart.options._stock && this.coll === 'yAxis') { key = options.top + ',' + options.height; if (!panes[key] && labelOptions.enabled) { // do it only for the first Y axis of each pane if (labelOptions.x === 15) { // default labelOptions.x = 0; } if (labelOptions.align === undefined) { labelOptions.align = 'right'; } panes[key] = 1; return 'right'; } } return proceed.call(this, [].slice.call(arguments, 1)); }); // Override getPlotLinePath to allow for multipane charts wrap(Axis.prototype, 'getPlotLinePath', function (proceed, value, lineWidth, old, force, translatedValue) { var axis = this, series = (this.isLinked && !this.series ? this.linkedParent.series : this.series), chart = axis.chart, renderer = chart.renderer, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, result = [], axes = [], //#3416 need a default array axes2, uniqueAxes; // Ignore in case of color Axis. #3360, #3524 if (axis.coll === 'colorAxis') { return proceed.apply(this, [].slice.call(arguments, 1)); } // Get the related axes based on series axes = (axis.isXAxis ? (defined(axis.options.yAxis) ? [chart.yAxis[axis.options.yAxis]] : map(series, function (S) { return S.yAxis; }) ) : (defined(axis.options.xAxis) ? [chart.xAxis[axis.options.xAxis]] : map(series, function (S) { return S.xAxis; }) ) ); // Get the related axes based options.*Axis setting #2810 axes2 = (axis.isXAxis ? chart.yAxis : chart.xAxis); each(axes2, function (A) { if (defined(A.options.id) ? A.options.id.indexOf('navigator') === -1 : true) { var a = (A.isXAxis ? 'yAxis' : 'xAxis'), rax = (defined(A.options[a]) ? chart[a][A.options[a]] : chart[a][0]); if (axis === rax) { axes.push(A); } } }); // Remove duplicates in the axes array. If there are no axes in the axes array, // we are adding an axis without data, so we need to populate this with grid // lines (#2796). uniqueAxes = axes.length ? [] : [axis.isXAxis ? chart.yAxis[0] : chart.xAxis[0]]; //#3742 each(axes, function (axis2) { if (inArray(axis2, uniqueAxes) === -1) { uniqueAxes.push(axis2); } }); translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); if (!isNaN(translatedValue)) { if (axis.horiz) { each(uniqueAxes, function (axis2) { var skip; y1 = axis2.pos; y2 = y1 + axis2.len; x1 = x2 = mathRound(translatedValue + axis.transB); if (x1 < axisLeft || x1 > axisLeft + axis.width) { // outside plot area if (force) { x1 = x2 = mathMin(mathMax(axisLeft, x1), axisLeft + axis.width); } else { skip = true; } } if (!skip) { result.push('M', x1, y1, 'L', x2, y2); } }); } else { each(uniqueAxes, function (axis2) { var skip; x1 = axis2.pos; x2 = x1 + axis2.len; y1 = y2 = mathRound(axisTop + axis.height - translatedValue); if (y1 < axisTop || y1 > axisTop + axis.height) { // outside plot area if (force) { y1 = y2 = mathMin(mathMax(axisTop, y1), axis.top + axis.height); } else { skip = true; } } if (!skip) { result.push('M', x1, y1, 'L', x2, y2); } }); } } if (result.length > 0) { return renderer.crispPolyLine(result, lineWidth || 1); } else { return null; //#3557 getPlotLinePath in regular Highcharts also returns null } }); // Override getPlotBandPath to allow for multipane charts Axis.prototype.getPlotBandPath = function (from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true), result = [], i; if (path && toPath && path.toString() !== toPath.toString()) { // Go over each subpath for (i = 0; i < path.length; i += 6) { result.push('M', path[i + 1], path[i + 2], 'L', path[i + 4], path[i + 5], toPath[i + 4], toPath[i + 5], toPath[i + 1], toPath[i + 2]); } } else { // outside the axis area result = null; } return result; }; // Function to crisp a line with multiple segments SVGRenderer.prototype.crispPolyLine = function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line var i; for (i = 0; i < points.length; i = i + 6) { if (points[i + 1] === points[i + 4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[i + 1] = points[i + 4] = mathRound(points[i + 1]) - (width % 2 / 2); } if (points[i + 2] === points[i + 5]) { points[i + 2] = points[i + 5] = mathRound(points[i + 2]) + (width % 2 / 2); } } return points; }; if (Renderer === Highcharts.VMLRenderer) { VMLRenderer.prototype.crispPolyLine = SVGRenderer.prototype.crispPolyLine; } // Wrapper to hide the label wrap(Axis.prototype, 'hideCrosshair', function (proceed, i) { proceed.call(this, i); if (!defined(this.crossLabelArray)) { return; } if (defined(i)) { if (this.crossLabelArray[i]) { this.crossLabelArray[i].hide(); } } else { each(this.crossLabelArray, function (crosslabel) { crosslabel.hide(); }); } }); // Wrapper to draw the label wrap(Axis.prototype, 'drawCrosshair', function (proceed, e, point) { // Draw the crosshair proceed.call(this, e, point); // Check if the label has to be drawn if (!defined(this.crosshair.label) || !this.crosshair.label.enabled || !defined(point)) { return; } var chart = this.chart, options = this.options.crosshair.label, // the label's options axis = this.isXAxis ? 'x' : 'y', // axis name horiz = this.horiz, // axis orientation opposite = this.opposite, // axis position left = this.left, // left position top = this.top, // top position crossLabel = this.crossLabel, // reference to the svgElement posx, posy, crossBox, formatOption = options.format, formatFormat = '', limit; // If the label does not exist yet, create it. if (!crossLabel) { crossLabel = this.crossLabel = chart.renderer.label() .attr({ align: options.align || (horiz ? 'center' : opposite ? (this.labelAlign === 'right' ? 'right' : 'left') : (this.labelAlign === 'left' ? 'left' : 'center')), zIndex: 12, height: horiz ? 16 : UNDEFINED, fill: options.backgroundColor || (this.series[0] && this.series[0].color) || 'gray', padding: pick(options.padding, 2), stroke: options.borderColor || null, 'stroke-width': options.borderWidth || 0 }) .css(extend({ color: 'white', fontWeight: 'normal', fontSize: '11px', textAlign: 'center' }, options.style)) .add(); } if (horiz) { posx = point.plotX + left; posy = top + (opposite ? 0 : this.height); } else { posx = opposite ? this.width + left : 0; posy = point.plotY + top; } // if the crosshair goes out of view (too high or too low, hide it and hide the label) if (posy < top || posy > top + this.height) { this.hideCrosshair(); return; } // TODO: Dynamic date formats like in Series.tooltipHeaderFormat. if (!formatOption && !options.formatter) { if (this.isDatetimeAxis) { formatFormat = '%b %d, %Y'; } formatOption = '{value' + (formatFormat ? ':' + formatFormat : '') + '}'; } // show the label crossLabel.attr({ text: formatOption ? format(formatOption, {value: point[axis]}) : options.formatter.call(this, point[axis]), x: posx, y: posy, visibility: VISIBLE }); crossBox = crossLabel.getBBox(); // now it is placed we can correct its position if (horiz) { if (((this.options.tickPosition === 'inside') && !opposite) || ((this.options.tickPosition !== 'inside') && opposite)) { posy = crossLabel.y - crossBox.height; } } else { posy = crossLabel.y - (crossBox.height / 2); } // check the edges if (horiz) { limit = { left: left - crossBox.x, right: left + this.width - crossBox.x }; } else { limit = { left: this.labelAlign === 'left' ? left : 0, right: this.labelAlign === 'right' ? left + this.width : chart.chartWidth }; } // left edge if (crossLabel.translateX < limit.left) { posx += limit.left - crossLabel.translateX; } // right edge if (crossLabel.translateX + crossBox.width >= limit.right) { posx -= crossLabel.translateX + crossBox.width - limit.right; } // show the crosslabel crossLabel.attr({x: posx, y: posy, visibility: VISIBLE}); }); /* **************************************************************************** * Start value compare logic * *****************************************************************************/ var seriesInit = seriesProto.init, seriesProcessData = seriesProto.processData, pointTooltipFormatter = Point.prototype.tooltipFormatter; /** * Extend series.init by adding a method to modify the y value used for plotting * on the y axis. This method is called both from the axis when finding dataMin * and dataMax, and from the series.translate method. */ seriesProto.init = function () { // Call base method seriesInit.apply(this, arguments); // Set comparison mode this.setCompare(this.options.compare); }; /** * The setCompare method can be called also from the outside after render time */ seriesProto.setCompare = function (compare) { // Set or unset the modifyValue method this.modifyValue = (compare === 'value' || compare === 'percent') ? function (value, point) { var compareValue = this.compareValue; if (value !== UNDEFINED) { // #2601 // get the modified value value = compare === 'value' ? value - compareValue : // compare value value = 100 * (value / compareValue) - 100; // compare percent // record for tooltip etc. if (point) { point.change = value; } } return value; } : null; // Mark dirty if (this.chart.hasRendered) { this.isDirty = true; } }; /** * Extend series.processData by finding the first y value in the plot area, * used for comparing the following values */ seriesProto.processData = function () { var series = this, i = 0, processedXData, processedYData, length; // call base method seriesProcessData.apply(this, arguments); if (series.xAxis && series.processedYData) { // not pies // local variables processedXData = series.processedXData; processedYData = series.processedYData; length = processedYData.length; // find the first value for comparison for (; i < length; i++) { if (typeof processedYData[i] === NUMBER && processedXData[i] >= series.xAxis.min) { series.compareValue = processedYData[i]; break; } } } }; /** * Modify series extremes */ wrap(seriesProto, 'getExtremes', function (proceed) { proceed.apply(this, [].slice.call(arguments, 1)); if (this.modifyValue) { this.dataMax = this.modifyValue(this.dataMax); this.dataMin = this.modifyValue(this.dataMin); } }); /** * Add a utility method, setCompare, to the Y axis */ Axis.prototype.setCompare = function (compare, redraw) { if (!this.isXAxis) { each(this.series, function (series) { series.setCompare(compare); }); if (pick(redraw, true)) { this.chart.redraw(); } } }; /** * Extend the tooltip formatter by adding support for the point.change variable * as well as the changeDecimals option */ Point.prototype.tooltipFormatter = function (pointFormat) { var point = this; pointFormat = pointFormat.replace( '{point.change}', (point.change > 0 ? '+' : '') + Highcharts.numberFormat(point.change, pick(point.series.tooltipOptions.changeDecimals, 2)) ); return pointTooltipFormatter.apply(this, [pointFormat]); }; /* **************************************************************************** * End value compare logic * *****************************************************************************/ /** * Extend the Series prototype to create a separate series clip box. This is related * to using multiple panes, and a future pane logic should incorporate this feature (#2754). */ wrap(Series.prototype, 'render', function (proceed) { // Only do this on stock charts (#2939), and only if the series type handles clipping // in the animate method (#2975). if (this.chart.options._stock) { // First render, initial clip box if (!this.clipBox && this.animate) { this.clipBox = merge(this.chart.clipBox); this.clipBox.width = this.xAxis.len; this.clipBox.height = this.yAxis.len; // On redrawing, resizing etc, update the clip rectangle } else if (this.chart[this.sharedClipKey]) { stop(this.chart[this.sharedClipKey]); // #2998 this.chart[this.sharedClipKey].attr({ width: this.xAxis.len, height: this.yAxis.len }); } } proceed.call(this); }); // global variables extend(Highcharts, { // Constructors Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, error: error, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, map: map, merge: merge, splat: splat, extendClass: extendClass, pInt: pInt, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
src/nls/es/strings.js
ropik/brackets
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * 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. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ /** * Errors */ // General file io error strings "GENERIC_ERROR" : "(error {0})", "NOT_FOUND_ERR" : "No se pudo encontrar el archivo/directorio.", "NOT_READABLE_ERR" : "No se pudo leer el archivo/directorio.", "EXCEEDS_MAX_FILE_SIZE" : "Los archivos de más de {0} MB no se pueden abrir en {APP_NAME}.", "NO_MODIFICATION_ALLOWED_ERR" : "El directorio de destino no se puede modificar.", "NO_MODIFICATION_ALLOWED_ERR_FILE" : "Los permisos no permiten hacer modificaciones.", "CONTENTS_MODIFIED_ERR" : "El archivo fue modificado fuera de {APP_NAME}.", "UNSUPPORTED_ENCODING_ERR" : "{APP_NAME} actualmente solo soporta archivos codificados como UTF-8.", "FILE_EXISTS_ERR" : "El archivo ya existe.", "FILE" : "archivo", "FILE_TITLE" : "archivo", "DIRECTORY" : "directorio", "DIRECTORY_TITLE" : "directorio", "DIRECTORY_NAMES_LEDE" : "nombres de directorios", "FILENAMES_LEDE" : "nombres de archivos", "FILENAME" : "nombre de archivo", "DIRECTORY_NAME" : "nombre de directorio", // Project error strings "ERROR_LOADING_PROJECT" : "Error abriendo el proyecto", "OPEN_DIALOG_ERROR" : "Ha ocurrido un error al mostrar el aviso de apertura de archivo. (error {0})", "REQUEST_NATIVE_FILE_SYSTEM_ERROR" : "Ha ocurrido un error al intentar abrir el directorio <span class='dialog-filename'>{0}</span>. (error {1})", "READ_DIRECTORY_ENTRIES_ERROR" : "Ha ocurrido un error al leer los contenidos del directorio <span class='dialog-filename'>{0}</span>. (error {1})", // File open/save error string "ERROR_OPENING_FILE_TITLE" : "Error abriendo el archivo", "ERROR_OPENING_FILE" : "Ha ocurrido un error al intentar abrir el archivo <span class='dialog-filename'>{0}</span>. {1}", "ERROR_OPENING_FILES" : "Ha ocurrido un error al intentar abrir los siguientes archivos:", "ERROR_RELOADING_FILE_TITLE" : "Error recargando cambios desde disco", "ERROR_RELOADING_FILE" : "Ha ocurrido un error al intentar recargar el archivo <span class='dialog-filename'>{0}</span>. {1}", "ERROR_SAVING_FILE_TITLE" : "Error guardando el archivo", "ERROR_SAVING_FILE" : "Ha ocurrido un error al intentar guardar el archivo <span class='dialog-filename'>{0}</span>. {1}", "ERROR_RENAMING_FILE_TITLE" : "Error renombrando el {0}", "ERROR_RENAMING_FILE" : "Ha ocurrido un error al intentar renombrar el {2} <span class='dialog-filename'>{0}</span>. {1}", "ERROR_DELETING_FILE_TITLE" : "Error eliminando el {0}", "ERROR_DELETING_FILE" : "Ha ocurrido un error al intentar eliminar el {2} <span class='dialog-filename'>{0}</span>. {1}", "INVALID_FILENAME_TITLE" : "{0} inválido", "INVALID_FILENAME_MESSAGE" : "Los {0} no pueden utilizar ninguna palabra reservada por el sistema, terminar con puntos (.) o utilizar cualquiera de los siguientes caracteres: <code class='emphasized'>{1}</code>", "ENTRY_WITH_SAME_NAME_EXISTS" : "Ya existe un archivo o directorio con el nombre <span class='dialog-filename'>{0}</span>.", "ERROR_CREATING_FILE_TITLE" : "Error creando {0}", "ERROR_CREATING_FILE" : "Ha ocurrido un error al intentar crear el {0} <span class='dialog-filename'>{1}</span>. {2}", "ERROR_MIXED_DRAGDROP" : "No es posible abrir una carpeta y otros archivos al mismo tiempo.", // User key map error strings "ERROR_KEYMAP_TITLE" : "Ocurrió un error leyendo los atajos de teclado", "ERROR_KEYMAP_CORRUPT" : "El archivo de atajos de teclado no tiene un formato JSON válido. El archivo se abrirá para que puedas corregir el formato.", "ERROR_LOADING_KEYMAP" : "El archivo de atajos de teclado no está codificado como UTF-8 y no puede ser cargado.", "ERROR_RESTRICTED_COMMANDS" : "No puedes reasignar atajos de teclado a los siguientes comandos: {0}", "ERROR_RESTRICTED_SHORTCUTS" : "No puedes reasignar los siguientes atajos de teclado: {0}", "ERROR_MULTIPLE_SHORTCUTS" : "Estas reasignando múltiples atajos de teclado a los siguientes comandos: {0}", "ERROR_DUPLICATE_SHORTCUTS" : "Hay múltiples apariciones de los siguientes atajos de teclado: {0}", "ERROR_INVALID_SHORTCUTS" : "Los siguientes atajos de teclado son inválidos: {0}", "ERROR_NONEXISTENT_COMMANDS" : "Estas asignando atajos de teclado a commandos inexistentes: {0}", // Application preferences corrupt error strings "ERROR_PREFS_CORRUPT_TITLE" : "Error leyendo las preferencias", "ERROR_PREFS_CORRUPT" : "El archivo de preferencias no tiene un formato JSON válido. El archivo se abrirá para que puedas corregir el formato. Luego deberás reiniciar {APP_NAME} para que los cambios surtan efecto.", // Application error strings "ERROR_IN_BROWSER_TITLE" : "Vaya... parece que {APP_NAME} todavía no funciona en navegadores.", "ERROR_IN_BROWSER" : "{APP_NAME} está desarrollado en HTML, pero por ahora funciona como una aplicación de escritorio para que puedas editar archivos localmente. Por favor, utiliza la aplicación del repositorio <b>github.com/adobe/brackets-shell</b> para ejecutar {APP_NAME}.", // FileIndexManager error string "ERROR_MAX_FILES_TITLE" : "Error indexando archivos", "ERROR_MAX_FILES" : "Este proyecto contiene más de 30.000 archivos. Funciones que operan sobre múltiples archivos pueden estar deshabilitadas o funcionar igual que si el proyecto estuviese vacío. <a href='https://github.com/adobe/brackets/wiki/Large-Projects'>Leer más acerca de cómo trabajar con proyectos grandes</a>.", // Live Preview error strings "ERROR_LAUNCHING_BROWSER_TITLE" : "Error iniciando el navegador", "ERROR_CANT_FIND_CHROME" : "No se pudo encontrar el navegador Google Chrome. Por favor, asegúrate que esté instalado correctamente.", "ERROR_LAUNCHING_BROWSER" : "Ha ocurrido un error al iniciar el navegador. (error {0})", "LIVE_DEVELOPMENT_ERROR_TITLE" : "Error en la Vista previa dinámica", "LIVE_DEVELOPMENT_RELAUNCH_TITLE" : "Conectando con el navegador", "LIVE_DEVELOPMENT_ERROR_MESSAGE" : "Para poder iniciar el modo de Vista previa dinámica, Chrome debe ser iniciado habilitando la depuración remota.<br /><br />¿Quieres reiniciar Chrome y habilitar la depuración remota?<br /><br />", "LIVE_DEV_LOADING_ERROR_MESSAGE" : "No se pudo cargar la página para la Vista previa dinámica.", "LIVE_DEV_NEED_HTML_MESSAGE" : "Abra un archivo HTML o asegúrate de que haya un index.html en tu proyecto para poder iniciar el modo de Vista previa dinámica.", "LIVE_DEV_NEED_BASEURL_MESSAGE" : "Necesitas especificar una URL base en este proyecto para poder iniciar la Vista previa dinámica con archivos de servidor.", "LIVE_DEV_SERVER_NOT_READY_MESSAGE" : "Error iniciando el servidor HTTP para la Vista previa dinámica. Vuelve a intentarlo, por favor.", "LIVE_DEVELOPMENT_INFO_TITLE" : "¡Bienvenido a la Vista previa dinámica!", "LIVE_DEVELOPMENT_INFO_MESSAGE" : "Vista previa dinámica conecta {APP_NAME} con tu navegador. Lanza una vista previa de tu archivo HTML en el navegador y la actualiza a medida que modificas tu código.<br /><br />En esta versión preliminar de {APP_NAME}, el modo de Vista previa dinámica sólo funciona para cambios de <strong>archivos CSS o HTML</strong> y únicamente con <strong>Google Chrome</strong>. Los cambios en los archivos Javascript son recargados automáticamente cuando se guardan.<br /><br />(No volverás a ver este mensaje.)", "LIVE_DEVELOPMENT_TROUBLESHOOTING" : "Para más información, consulta <a href='{0}' title='{0}'>Resolución de Problemas de conexión en Vista previa dinámica</a>.", "LIVE_DEV_STATUS_TIP_NOT_CONNECTED" : "Vista previa dinámica", "LIVE_DEV_STATUS_TIP_PROGRESS1" : "Vista previa dinámica: Conectando\u2026", "LIVE_DEV_STATUS_TIP_PROGRESS2" : "Vista previa dinámica: Inicializando\u2026", "LIVE_DEV_STATUS_TIP_CONNECTED" : "Terminar la Vista previa dinámica", "LIVE_DEV_STATUS_TIP_OUT_OF_SYNC" : "Vista previa dinámica (guarda el archivo para actualizar)", "LIVE_DEV_STATUS_TIP_SYNC_ERROR" : "Vista previa dinámica (no se está actualizando debido a un error de sintaxis)", "LIVE_DEV_DETACHED_REPLACED_WITH_DEVTOOLS" : "Vista previa dinámica se ha detenido porque se han abierto las herramientas de desarrollo", "LIVE_DEV_DETACHED_TARGET_CLOSED" : "Vista previa dinámica se ha detenido porque se ha cerrado la página en el navegador", "LIVE_DEV_NAVIGATED_AWAY" : "Vista previa dinámica se ha detenido porque se ha accedido a una página que no es parte del proyecto actual", "LIVE_DEV_CLOSED_UNKNOWN_REASON" : "Vista previa dinámica se ha detenido por motivos desconocidos ({0})", "SAVE_CLOSE_TITLE" : "Guardar cambios", "SAVE_CLOSE_MESSAGE" : "¿Quieres guardar los cambios existentes en el documento <span class='dialog-filename'>{0}</span>?", "SAVE_CLOSE_MULTI_MESSAGE" : "¿Quieres guardar tus cambios en los siguientes documentos?", "EXT_MODIFIED_TITLE" : "Cambios externos", "CONFIRM_FOLDER_DELETE_TITLE" : "Confirmar eliminación", "CONFIRM_FOLDER_DELETE" : "¿Estás seguro que deseas eliminar el directorio <span class='dialog-filename'>{0}</span>?", "FILE_DELETED_TITLE" : "Archivo eliminado", "EXT_MODIFIED_WARNING" : "<span class='dialog-filename'>{0}</span> ha sido modificado en el disco.<br /><br />¿Deseas guardar el archivo y sobrescribir esos cambios?", "EXT_MODIFIED_MESSAGE" : "<span class='dialog-filename'>{0}</span> ha sido modificado, pero también tiene cambios en {APP_NAME}.<br /><br />¿Qué versión quieres conservar?", "EXT_DELETED_MESSAGE" : "<span class='dialog-filename'>{0}</span> ha sido eliminado, pero tiene cambios sin guardar en {APP_NAME}.<br /><br />¿Quieres conservar tus cambios?", // Generic dialog/button labels "DONE" : "Aceptar", "OK" : "Aceptar", "CANCEL" : "Cancelar", "DONT_SAVE" : "No guardar", "SAVE" : "Guardar", "DELETE" : "Eliminar", "SAVE_AS" : "Guardar como\u2026", "SAVE_AND_OVERWRITE" : "Sobrescribir", "BUTTON_YES" : "Sí", "BUTTON_NO" : "No", // Find, Replace, Find in Files "FIND_RESULT_COUNT" : "{0} de {1}", "FIND_NO_RESULTS" : "No hay resultados", "FIND_QUERY_PLACEHOLDER" : "Buscar\u2026", "REPLACE_PLACEHOLDER" : "Reemplazar con\u2026", "BUTTON_REPLACE_ALL" : "Todo\u2026", "BUTTON_REPLACE_ALL_IN_FILES" : "Reemplazar\u2026", "BUTTON_REPLACE" : "Reemplazar", "BUTTON_NEXT" : "\u25B6", "BUTTON_PREV" : "\u25C0", "BUTTON_NEXT_HINT" : "Siguiente coincidencia", "BUTTON_PREV_HINT" : "Anterior coincidencia", "BUTTON_CASESENSITIVE_HINT" : "Sensible a mayúsculas", "BUTTON_REGEXP_HINT" : "Expresión regular", "REPLACE_WITHOUT_UNDO_WARNING_TITLE": "Reemplazar sin deshacer", "REPLACE_WITHOUT_UNDO_WARNING" : "Dado que hay más de {0} archivos que necesitan ser modificados, {APP_NAME} modificará los archivos no abiertos en el disco.<br />Por lo tanto, no será posible deshacer los reemplazos en esos archivos.", "BUTTON_REPLACE_WITHOUT_UNDO" : "Reemplazar sin deshacer", "OPEN_FILE" : "Abrir archivo", "SAVE_FILE_AS" : "Guardar archivo", "CHOOSE_FOLDER" : "Elige una carpeta", "RELEASE_NOTES" : "Notas sobre la versión", "NO_UPDATE_TITLE" : "¡Estás actualizado!", "NO_UPDATE_MESSAGE" : "Estás utilizando la última versión de {APP_NAME}.", // Find and Replace "FIND_REPLACE_TITLE_LABEL" : "Reemplazar", "FIND_REPLACE_TITLE_WITH" : "con", "FIND_TITLE_LABEL" : "Se encontró", "FIND_TITLE_SUMMARY" : "&mdash; {0} {1} {2} en {3}", // Find in Files "FIND_NUM_FILES" : "{0} {1}", "FIND_IN_FILES_SCOPED" : "en <span class='dialog-filename'>{0}</span>", "FIND_IN_FILES_NO_SCOPE" : "en el proyecto", "FIND_IN_FILES_ZERO_FILES" : "El filtro excluye todos los archivos {0}", "FIND_IN_FILES_FILE" : "archivo", "FIND_IN_FILES_FILES" : "archivos", "FIND_IN_FILES_MATCH" : "coincidencia", "FIND_IN_FILES_MATCHES" : "coincidencias", "FIND_IN_FILES_MORE_THAN" : "Más de ", "FIND_IN_FILES_PAGING" : "{0}&mdash;{1}", "FIND_IN_FILES_FILE_PATH" : "<span class='dialog-filename'>{0}</span> {2} <span class='dialog-path'>{1}</span>", "FIND_IN_FILES_EXPAND_COLLAPSE" : "Ctrl/Cmd clic para expandir/colapsar todo", "REPLACE_IN_FILES_ERRORS_TITLE" : "Errores al reemplazar", "REPLACE_IN_FILES_ERRORS" : "Los siguientes archivos no fueron modificados porque cambiaron después de realizar la búsqueda o no pueden ser escritos.", "ERROR_FETCHING_UPDATE_INFO_TITLE" : "Error obteniendo información sobre actualizaciones", "ERROR_FETCHING_UPDATE_INFO_MSG" : "Ocurrió un problema al obtener la información sobre las últimas actualizaciones desde el servidor. Por favor, asegúrate de estar conectado a internet y vuelve a intentarlo.", // File exclusion filters "NEW_FILE_FILTER" : "Nuevo conjunto de filtros\u2026", "CLEAR_FILE_FILTER" : "No excluir archivos", "NO_FILE_FILTER" : "No hay archivos excluidos", "EXCLUDE_FILE_FILTER" : "Excluir {0}", "EDIT_FILE_FILTER" : "Editar\u2026", "FILE_FILTER_DIALOG" : "Editar conjunto de filtros", "FILE_FILTER_INSTRUCTIONS" : "Excluir archivos y carpetas que coincidan con alguna de las siguientes cadenas / subcadenas o <a href='{0}' title='{0}'>comodines</a>. Ingrese una cadena por línea.", "FILTER_NAME_PLACEHOLDER" : "Nombrar este conjunto de filtros (opcional)", "FILE_FILTER_CLIPPED_SUFFIX" : "y {0} más", "FILTER_COUNTING_FILES" : "Contando archivos\u2026", "FILTER_FILE_COUNT" : "Permite {0} de {1} archivos {2}", "FILTER_FILE_COUNT_ALL" : "Permite todos los {0} archivos {1}", // Quick Edit "ERROR_QUICK_EDIT_PROVIDER_NOT_FOUND" : "La Edición Rápida no está disponible para la posición actual del cursor", "ERROR_CSSQUICKEDIT_BETWEENCLASSES" : "Edición Rápida para CSS: ubique el cursor sobre el nombre de una clase", "ERROR_CSSQUICKEDIT_CLASSNOTFOUND" : "Edición Rápida para CSS: atributo de clase incompleto", "ERROR_CSSQUICKEDIT_IDNOTFOUND" : "Edición Rápida para CSS: atributo de identificación incompleto", "ERROR_CSSQUICKEDIT_UNSUPPORTEDATTR" : "Edición Rápida para CSS: ubique el cursor sobre una etiqueta, clase o id", "ERROR_TIMINGQUICKEDIT_INVALIDSYNTAX" : "Edición Rápida para Funciones de Temporización de CSS: sintaxis inválida", "ERROR_JSQUICKEDIT_FUNCTIONNOTFOUND" : "Edición Rápida para JS: ubique el cursor sobre el nombre de una función", // Quick Docs "ERROR_QUICK_DOCS_PROVIDER_NOT_FOUND" : "La Documentación Rápida no está disponible para la posición actual del cursor", /** * ProjectManager */ "PROJECT_LOADING" : "Cargando\u2026", "UNTITLED" : "Sin título", "WORKING_FILES" : "Área de trabajo", /** * MainViewManager */ "TOP" : "Arriba", "BOTTOM" : "Abajo", "LEFT" : "Izquierda", "RIGHT" : "Derecha", "CMD_SPLITVIEW_NONE" : "No dividido", "CMD_SPLITVIEW_VERTICAL" : "División vertical", "CMD_SPLITVIEW_HORIZONTAL" : "División horizontal", "SPLITVIEW_MENU_TOOLTIP" : "Dividir el editor vertical u horizontalmente", "GEAR_MENU_TOOLTIP" : "Configurar el área de trabajo", "SPLITVIEW_INFO_TITLE" : "Ya está abierto", "SPLITVIEW_MULTIPANE_WARNING" : "El archivo ya está abierto en otro panel. Próximamente {APP_NAME} soportará abrir el mismo archivo en más de un panel. Hasta entonces, el archivo se mostrará en el panel en el cual ya está abierto.<br /><br />(Sólo verá este mensaje una vez.)", /** * Keyboard modifier names */ "KEYBOARD_CTRL" : "Ctrl", "KEYBOARD_SHIFT" : "May", "KEYBOARD_SPACE" : "Espacio", /** * StatusBar strings */ "STATUSBAR_CURSOR_POSITION" : "Línea {0}, Columna {1}", "STATUSBAR_SELECTION_CH_SINGULAR" : " \u2014 {0} columna seleccionada", "STATUSBAR_SELECTION_CH_PLURAL" : " \u2014 {0} columnas seleccionadas", "STATUSBAR_SELECTION_LINE_SINGULAR" : " \u2014 {0} línea seleccionada", "STATUSBAR_SELECTION_LINE_PLURAL" : " \u2014 {0} líneas seleccionadas", "STATUSBAR_SELECTION_MULTIPLE" : " \u2014 {0} selecciones", "STATUSBAR_INDENT_TOOLTIP_SPACES" : "Haz clic para usar espacios en la sangría", "STATUSBAR_INDENT_TOOLTIP_TABS" : "Haz clic para usar tabulaciones en la sangría", "STATUSBAR_INDENT_SIZE_TOOLTIP_SPACES" : "Haz clic para cambiar el número de espacios usados en la sangría", "STATUSBAR_INDENT_SIZE_TOOLTIP_TABS" : "Haz clic para cambiar el ancho de las tabulaciones", "STATUSBAR_SPACES" : "Espacios:", "STATUSBAR_TAB_SIZE" : "Tamaño del tabulador:", "STATUSBAR_LINE_COUNT_SINGULAR" : "\u2014 {0} línea", "STATUSBAR_LINE_COUNT_PLURAL" : "\u2014 {0} líneas", "STATUSBAR_USER_EXTENSIONS_DISABLED" : "Extensiones deshabilitadas", "STATUSBAR_INSERT" : "INS", "STATUSBAR_OVERWRITE" : "SOB", "STATUSBAR_INSOVR_TOOLTIP" : "Haz clic para intercambiar entre el modo insertar (INS) y el modo sobrescribir (SOB)", "STATUSBAR_LANG_TOOLTIP" : "Haz clic para cambiar el tipo de archivo", "STATUSBAR_CODE_INSPECTION_TOOLTIP" : "{0}. Haz clic para mostrar/ocultar el panel de reportes.", "STATUSBAR_DEFAULT_LANG" : "(por defecto)", "STATUSBAR_SET_DEFAULT_LANG" : "Marcar como predeterminado para los archivos .{0}", // CodeInspection: errors/warnings "ERRORS_PANEL_TITLE_MULTIPLE" : "Problemas de {0}", "SINGLE_ERROR" : "1 problema de {0}", "MULTIPLE_ERRORS" : "{1} problemas de {0}", "NO_ERRORS" : "No se encontraron problemas de {0} - ¡Buen trabajo!", "NO_ERRORS_MULTIPLE_PROVIDER" : "No se encontraron problemas - ¡Buen trabajo!", "LINT_DISABLED" : "La inspección de código está deshabilitada", "NO_LINT_AVAILABLE" : "No hay inspección de código disponible para {0}", "NOTHING_TO_LINT" : "No hay nada para inspeccionar", "LINTER_TIMED_OUT" : "{0} ha agotado el tiempo después de esperar {1} ms", "LINTER_FAILED" : "{0} terminó con error: {1}", /** * Command Name Constants */ // File menu commands "FILE_MENU" : "Archivo", "CMD_FILE_NEW_UNTITLED" : "Nuevo", "CMD_FILE_NEW" : "Nuevo archivo", "CMD_FILE_NEW_FOLDER" : "Nueva carpeta", "CMD_FILE_OPEN" : "Abrir\u2026", "CMD_ADD_TO_WORKING_SET" : "Abrir en el área de trabajo", "CMD_OPEN_DROPPED_FILES" : "Abrir archivos soltados", "CMD_OPEN_FOLDER" : "Abrir carpeta\u2026", "CMD_FILE_CLOSE" : "Cerrar", "CMD_FILE_CLOSE_ALL" : "Cerrar todo", "CMD_FILE_CLOSE_LIST" : "Cerrar lista", "CMD_FILE_CLOSE_OTHERS" : "Cerrar otros", "CMD_FILE_CLOSE_ABOVE" : "Cerrar otros por encima", "CMD_FILE_CLOSE_BELOW" : "Cerrar otros por debajo", "CMD_FILE_SAVE" : "Guardar", "CMD_FILE_SAVE_ALL" : "Guardar todo", "CMD_FILE_SAVE_AS" : "Guardar como\u2026", "CMD_LIVE_FILE_PREVIEW" : "Vista previa dinámica", "CMD_RELOAD_LIVE_PREVIEW" : "Recargar la Vista previa dinámica", "CMD_PROJECT_SETTINGS" : "Configuración del proyecto\u2026", "CMD_FILE_RENAME" : "Renombrar", "CMD_FILE_DELETE" : "Eliminar", "CMD_INSTALL_EXTENSION" : "Instalar extensión\u2026", "CMD_EXTENSION_MANAGER" : "Gestionar extensiones\u2026", "CMD_FILE_REFRESH" : "Actualizar árbol de archivos", "CMD_QUIT" : "Salir", // Used in native File menu on Windows "CMD_EXIT" : "Salir", // Edit menu commands "EDIT_MENU" : "Edición", "CMD_UNDO" : "Deshacer", "CMD_REDO" : "Rehacer", "CMD_CUT" : "Cortar", "CMD_COPY" : "Copiar", "CMD_PASTE" : "Pegar", "CMD_SELECT_ALL" : "Seleccionar todo", "CMD_SELECT_LINE" : "Seleccionar línea", "CMD_SPLIT_SEL_INTO_LINES" : "Dividir selección en líneas", "CMD_ADD_CUR_TO_NEXT_LINE" : "Agregar cursor a la siguiente línea", "CMD_ADD_CUR_TO_PREV_LINE" : "Agregar cursor a la línea anterior", "CMD_INDENT" : "Aumentar sangría", "CMD_UNINDENT" : "Disminuir sangría", "CMD_DUPLICATE" : "Duplicar", "CMD_DELETE_LINES" : "Eliminar línea", "CMD_COMMENT" : "Comentar/Descomentar línea", "CMD_BLOCK_COMMENT" : "Comentar/Descomentar bloque", "CMD_LINE_UP" : "Subir línea", "CMD_LINE_DOWN" : "Bajar línea", "CMD_OPEN_LINE_ABOVE" : "Crear línea arriba", "CMD_OPEN_LINE_BELOW" : "Crear línea abajo", "CMD_TOGGLE_CLOSE_BRACKETS" : "Completar paréntesis automáticamente", "CMD_SHOW_CODE_HINTS" : "Mostrar sugerencias de código", // Search menu commands "FIND_MENU" : "Buscar", "CMD_FIND" : "Buscar", "CMD_FIND_NEXT" : "Buscar siguiente", "CMD_FIND_PREVIOUS" : "Buscar anterior", "CMD_FIND_ALL_AND_SELECT" : "Buscar todo y seleccionar", "CMD_ADD_NEXT_MATCH" : "Agregar la siguiente coincidencia a la selección", "CMD_SKIP_CURRENT_MATCH" : "Omitir y agregar la siguiente coincidencia", "CMD_FIND_IN_FILES" : "Buscar en archivos", "CMD_FIND_IN_SELECTED" : "Buscar en el archivo/directorio seleccionado", "CMD_FIND_IN_SUBTREE" : "Buscar en\u2026", "CMD_REPLACE" : "Reemplazar", "CMD_REPLACE_IN_FILES" : "Reemplazar en archivos", "CMD_REPLACE_IN_SELECTED" : "Reemplazar en el archivo/directorio seleccionado", "CMD_REPLACE_IN_SUBTREE" : "Reemplazar en\u2026", // View menu commands "VIEW_MENU" : "Ver", "CMD_HIDE_SIDEBAR" : "Ocultar menú lateral", "CMD_SHOW_SIDEBAR" : "Mostrar menú lateral", "CMD_INCREASE_FONT_SIZE" : "Aumentar tamaño de fuente", "CMD_DECREASE_FONT_SIZE" : "Disminuir tamaño de fuente", "CMD_RESTORE_FONT_SIZE" : "Restablecer tamaño de fuente", "CMD_SCROLL_LINE_UP" : "Desplazar hacia arriba", "CMD_SCROLL_LINE_DOWN" : "Desplazar hacia abajo", "CMD_TOGGLE_LINE_NUMBERS" : "Mostrar números de línea", "CMD_TOGGLE_ACTIVE_LINE" : "Resaltar línea actual", "CMD_TOGGLE_WORD_WRAP" : "Habilitar ajuste de línea", "CMD_LIVE_HIGHLIGHT" : "Resaltado en Vista previa dinámica", "CMD_VIEW_TOGGLE_INSPECTION" : "Inspeccionar el código al guardar", "CMD_WORKINGSET_SORT_BY_ADDED" : "Ordenar por Añadido", "CMD_WORKINGSET_SORT_BY_NAME" : "Ordenar por Nombre", "CMD_WORKINGSET_SORT_BY_TYPE" : "Ordenar por Tipo", "CMD_WORKING_SORT_TOGGLE_AUTO" : "Ordenación automática", "CMD_THEMES" : "Temas\u2026", // Navigate menu Commands "NAVIGATE_MENU" : "Navegación", "CMD_QUICK_OPEN" : "Apertura rápida", "CMD_GOTO_LINE" : "Ir a la línea", "CMD_GOTO_DEFINITION" : "Búsqueda rápida de definición", "CMD_GOTO_FIRST_PROBLEM" : "Ir al primer problema", "CMD_TOGGLE_QUICK_EDIT" : "Edición rápida", "CMD_TOGGLE_QUICK_DOCS" : "Documentación rápida", "CMD_QUICK_EDIT_PREV_MATCH" : "Coincidencia anterior", "CMD_QUICK_EDIT_NEXT_MATCH" : "Coincidencia siguiente", "CMD_CSS_QUICK_EDIT_NEW_RULE" : "Nueva regla", "CMD_NEXT_DOC" : "Documento siguiente", "CMD_PREV_DOC" : "Documento anterior", "CMD_SHOW_IN_TREE" : "Mostrar en el árbol de directorios", "CMD_SHOW_IN_EXPLORER" : "Mostrar en el Explorador", "CMD_SHOW_IN_FINDER" : "Mostrar en Finder", "CMD_SHOW_IN_OS" : "Mostrar en el Sistema Operativo", // Help menu commands "HELP_MENU" : "Ayuda", "CMD_CHECK_FOR_UPDATE" : "Buscar actualizaciones", "CMD_HOW_TO_USE_BRACKETS" : "Cómo utilizar {APP_NAME}", "CMD_SUPPORT" : "Soporte de {APP_NAME}", "CMD_SUGGEST" : "Sugerir una mejora", "CMD_RELEASE_NOTES" : "Notas de la versión", "CMD_GET_INVOLVED" : "Involúcrese", "CMD_SHOW_EXTENSIONS_FOLDER" : "Abrir carpeta de extensiones", "CMD_HOMEPAGE" : "Página principal de {APP_TITLE}", "CMD_TWITTER" : "{TWITTER_NAME} en Twitter", "CMD_ABOUT" : "Acerca de {APP_TITLE}", "CMD_OPEN_PREFERENCES" : "Abrir archivo de preferencias", "CMD_OPEN_KEYMAP" : "Abrir archivo de atajos de teclado", // Strings for main-view.html "EXPERIMENTAL_BUILD" : "versión experimental", "RELEASE_BUILD" : "versión", "DEVELOPMENT_BUILD" : "versión de desarrollo", "RELOAD_FROM_DISK" : "Volver a cargar desde disco", "KEEP_CHANGES_IN_EDITOR" : "Conservar los cambios del editor", "CLOSE_DONT_SAVE" : "Cerrar (No guardar)", "RELAUNCH_CHROME" : "Reiniciar Chrome", "ABOUT" : "Acerca de\u2026", "CLOSE" : "Cerrar", "ABOUT_TEXT_LINE1" : "Release {VERSION_MAJOR}.{VERSION_MINOR} {BUILD_TYPE} {VERSION}", "ABOUT_TEXT_BUILD_TIMESTAMP" : "construido el: ", "ABOUT_TEXT_LINE3" : "Los avisos, términos y condiciones pertenecientes a software de terceros se encuentran en <a href='{ADOBE_THIRD_PARTY}'>{ADOBE_THIRD_PARTY}</a> y se incluyen aquí como referencia.", "ABOUT_TEXT_LINE4" : "Puedes encontrar la documentación y código fuente en <a href='https://github.com/adobe/brackets/'>https://github.com/adobe/brackets/</a>", "ABOUT_TEXT_LINE5" : "Hecho con \u2764 y JavaScript por:", "ABOUT_TEXT_LINE6" : "Mucha gente (pero ahora mismo estamos teniendo problemas para cargar esos datos).", "ABOUT_TEXT_WEB_PLATFORM_DOCS" : "El contenido de Web Platform Docs y el logo de Web Platform están disponibles bajo Licencia de Reconocimiento de Creative Commons, <a href='{WEB_PLATFORM_DOCS_LICENSE}'>CC-BY 3.0 Unported</a>.", "UPDATE_NOTIFICATION_TOOLTIP" : "¡Hay una nueva versión de {APP_NAME} disponible! Haz clic aquí para ver más detalles.", "UPDATE_AVAILABLE_TITLE" : "Actualización disponible", "UPDATE_MESSAGE" : "¡Hay una nueva versión de {APP_NAME} disponible! Éstas son algunas de las nuevas características:", "GET_IT_NOW" : "¡Consíguelo ahora!", "PROJECT_SETTINGS_TITLE" : "Configuración del proyecto para: {0}", "PROJECT_SETTING_BASE_URL" : "URL base para Vista previa dinámica", "PROJECT_SETTING_BASE_URL_HINT" : "(deja en blanco para urls de tipo \"file\")", "BASEURL_ERROR_INVALID_PROTOCOL" : "El protocolo {0} no está soportado por la Vista previa dinámica. Por favor, utiliza http: o https: .", "BASEURL_ERROR_SEARCH_DISALLOWED" : "La URL base no puede contener parámetros de búsqueda como \"{0}\".", "BASEURL_ERROR_HASH_DISALLOWED" : "La URL base no puede contener hashes como \"{0}\".", "BASEURL_ERROR_INVALID_CHAR" : "Los caracteres especiales como '{0}' deben codificarse en formato %.", "BASEURL_ERROR_UNKNOWN_ERROR" : "Error desconocido analizando la URL base", "EMPTY_VIEW_HEADER" : "<em>Abra un archivo mientras este panel está enfocado</em>", // Strings for themes-settings.html and themes-general.html "CURRENT_THEME" : "Tema actual", "USE_THEME_SCROLLBARS" : "Usar las barras de desplazamiento del tema", "FONT_SIZE" : "Tamaño de letra", "FONT_FAMILY" : "Tipo de letra", "THEMES_SETTINGS" : "Preferencias de temas", // CSS Quick Edit "BUTTON_NEW_RULE" : "Nueva regla", // Extension Management strings "INSTALL" : "Instalar", "UPDATE" : "Actualizar", "REMOVE" : "Eliminar", "OVERWRITE" : "Sobrescribir", "CANT_REMOVE_DEV" : "Las extensiones en la carpeta \"dev\" se deben eliminar manualmente.", "CANT_UPDATE" : "La actualización no es compatible con esta versión de {APP_NAME}.", "CANT_UPDATE_DEV" : "Las extensiones en la carpeta \"dev\" no se pueden actualizar automáticamente.", "INSTALL_EXTENSION_TITLE" : "Instalar extensión", "UPDATE_EXTENSION_TITLE" : "Actualizar extensión", "INSTALL_EXTENSION_LABEL" : "URL de la extensión", "INSTALL_EXTENSION_HINT" : "URL del archivo zip de la extensión o del repositorio de Github", "INSTALLING_FROM" : "Instalando extensión desde {0}\u2026", "INSTALL_SUCCEEDED" : "¡Instalación completada!", "INSTALL_FAILED" : "Error en la instalación.", "CANCELING_INSTALL" : "Cancelando\u2026", "CANCELING_HUNG" : "Cancelando la instalación porque está tardando demasiado tiempo. Puede que se haya producido un error interno.", "INSTALL_CANCELED" : "Instalación cancelada.", "VIEW_COMPLETE_DESCRIPTION" : "Ver descripción completa", "VIEW_TRUNCATED_DESCRIPTION" : "Ver descripción corta", // These must match the error codes in ExtensionsDomain.Errors.* : "INVALID_ZIP_FILE" : "El contenido descargado no es un archivo zip válido.", "INVALID_PACKAGE_JSON" : "El archivo package.json no es válido (error: {0}).", "MISSING_PACKAGE_NAME" : "El archivo package.json no especifica un nombre de paquete.", "BAD_PACKAGE_NAME" : "{0} no es un nombre de paquete válido.", "MISSING_PACKAGE_VERSION" : "El archivo package.json no especifica la versión del paquete.", "INVALID_VERSION_NUMBER" : "El número de paquete de la versión ({0}) no es válido.", "INVALID_BRACKETS_VERSION" : "El código de compatibilidad de {APP_NAME} ({0}) no es válido.", "DISALLOWED_WORDS" : "Las palabras ({1}) no están permitidas en el campo {0}.", "API_NOT_COMPATIBLE" : "La extensión no es compatible con esta versión de {APP_NAME}. Está en la carpeta de extensiones deshabilitadas.", "MISSING_MAIN" : "El paquete no contiene el archivo main.js.", "EXTENSION_ALREADY_INSTALLED" : "Instalar este paquete sobrescribirá una extensión instalada previamente. ¿Deseas sobrescribir la antigua extensión?", "EXTENSION_SAME_VERSION" : "La versión de este paquete es la misma que la instalada actualmente. ¿Deseas sobrescribir la instalación actual?", "EXTENSION_OLDER_VERSION" : "La versión {0} de este paquete es más antigua que la instalada actualmente ({1}). ¿Deseas sobrescribir la instalación actual?", "DOWNLOAD_ID_IN_USE" : "Error interno: el ID de descarga ya está siendo utilizado.", "NO_SERVER_RESPONSE" : "No se puede conectar con el servidor.", "BAD_HTTP_STATUS" : "Archivo no encontrado en el servidor (HTTP {0}).", "CANNOT_WRITE_TEMP" : "No se pudo guardar la descarga en un archivo temporal.", "ERROR_LOADING" : "La extensión ha encontrado un error al arrancar.", "MALFORMED_URL" : "La URL no es válida. Por favor, comprueba que esté escrita correctamente.", "UNSUPPORTED_PROTOCOL" : "La URL debe ser una dirección http o https.", "UNKNOWN_ERROR" : "Error interno desconocido.", // For NOT_FOUND_ERR, see generic strings above "EXTENSION_MANAGER_TITLE" : "Gestor de extensiones", "EXTENSION_MANAGER_ERROR_LOAD" : "No se pudo acceder al registro de extensiones. Vuelve a intentarlo más tarde, por favor.", "INSTALL_EXTENSION_DRAG" : "Arrastrar el .zip aquí ó", "INSTALL_EXTENSION_DROP" : "Soltar el .zip para instalarlo", "INSTALL_EXTENSION_DROP_ERROR" : "La instalación/actualización fue abortada por los siguientes errores:", "INSTALL_FROM_URL" : "Instalar desde URL\u2026", "INSTALL_EXTENSION_VALIDATING" : "Validando\u2026", "EXTENSION_AUTHOR" : "Autor", "EXTENSION_DATE" : "Fecha", "EXTENSION_INCOMPATIBLE_NEWER" : "Esta extensión necesita una versión más actualizada de {APP_NAME}.", "EXTENSION_INCOMPATIBLE_OLDER" : "En estos momentos esta extensión sólo funciona con versiones anteriores de {APP_NAME}.", "EXTENSION_LATEST_INCOMPATIBLE_NEWER" : "La versión {0} de esta extensión necesita una versión superior de {APP_NAME}. Puedes instalar la versión anterior {1}.", "EXTENSION_LATEST_INCOMPATIBLE_OLDER" : "La versión {0} de esta extensión sólo funciona con versiones anteriores de {APP_NAME}. Puedes instalar la versión anterior {1}.", "EXTENSION_NO_DESCRIPTION" : "Sin descripción", "EXTENSION_MORE_INFO" : "Más información...", "EXTENSION_ERROR" : "Error en la extensión", "EXTENSION_KEYWORDS" : "Palabras clave", "EXTENSION_INSTALLED" : "Instalada", "EXTENSION_TRANSLATED_USER_LANG" : "Traducida a {0} idiomas, incluyendo el tuyo", "EXTENSION_TRANSLATED_GENERAL" : "Traducida a {0} idiomas", "EXTENSION_TRANSLATED_LANGS" : "Esta extension fue traducida a los siguientes idiomas: {0}", "EXTENSION_UPDATE_INSTALLED" : "La actualización de esta extensión se ha descargado y se instalará luego de recargar {APP_NAME}.", "EXTENSION_SEARCH_PLACEHOLDER" : "Buscar", "EXTENSION_MORE_INFO_LINK" : "Más", "BROWSE_EXTENSIONS" : "Explorar extensiones", "EXTENSION_MANAGER_REMOVE" : "Eliminar extensión", "EXTENSION_MANAGER_REMOVE_ERROR" : "No se pudo eliminar una o más extensiones: {0}. {APP_NAME} se recargará igualmente.", "EXTENSION_MANAGER_UPDATE" : "Actualizar extensión", "EXTENSION_MANAGER_UPDATE_ERROR" : "No se pudo actualizar una o más extensiones: {0}. {APP_NAME} se recargará igualmente.", "MARKED_FOR_REMOVAL" : "Marcada para eliminar", "UNDO_REMOVE" : "Deshacer", "MARKED_FOR_UPDATE" : "Marcada para actualizar", "UNDO_UPDATE" : "Deshacer", "CHANGE_AND_RELOAD_TITLE" : "Cambiar extensiones", "CHANGE_AND_RELOAD_MESSAGE" : "Para actualizar o eliminar las extensiones marcadas, necesitas recargar {APP_NAME}. Se solicitará confirmación para guardar los cambios pendientes.", "REMOVE_AND_RELOAD" : "Eliminar extensiones y recargar", "CHANGE_AND_RELOAD" : "Cambiar extensiones y recargar", "UPDATE_AND_RELOAD" : "Actualizar extensiones y recargar", "PROCESSING_EXTENSIONS" : "Procesando los cambios en las extensiones\u2026", "EXTENSION_NOT_INSTALLED" : "No se pudo eliminar la extensión {0} porque no se encuentra instalada.", "NO_EXTENSIONS" : "Todavía no hay ninguna extensión instalada.<br>Haz clic en la pestaña Disponibles para empezar.", "NO_EXTENSION_MATCHES" : "No hay extensiones que coincidan con tu búsqueda.", "REGISTRY_SANITY_CHECK_WARNING" : "NOTA: estas extensiones pueden provenir de autores diferentes a {APP_NAME}. Las extensiones no son revisadas y tiene todos los privilegios locales. Tenga cuidado cuando instala extensiones de una fuente desconocida.", "EXTENSIONS_INSTALLED_TITLE" : "Instaladas", "EXTENSIONS_AVAILABLE_TITLE" : "Disponibles", "EXTENSIONS_THEMES_TITLE" : "Temas", "EXTENSIONS_UPDATES_TITLE" : "Actualizaciones", "INLINE_EDITOR_NO_MATCHES" : "No hay coincidencias disponibles.", "INLINE_EDITOR_HIDDEN_MATCHES" : "Todas las coincidencias están colapsadas. Expanda los archivos listados a la derecha para ver coincidencias.", "CSS_QUICK_EDIT_NO_MATCHES" : "No hay reglas de CSS existentes que coincidan con tu selección.<br> Haz clic en \"Nueva regla\" para crear una.", "CSS_QUICK_EDIT_NO_STYLESHEETS" : "No hay hojas de estilos en tu proyecto.<br>Crea una para añadir reglas de CSS.", // Custom Viewers "IMAGE_VIEWER_LARGEST_ICON" : "más grande", /** * Unit names */ "UNIT_PIXELS" : "píxeles", // extensions/default/DebugCommands "DEBUG_MENU" : "Desarrollo", "ERRORS" : "Errores", "CMD_SHOW_DEV_TOOLS" : "Mostrar herramientas para desarrolladores", "CMD_REFRESH_WINDOW" : "Recargar con extensiones", "CMD_RELOAD_WITHOUT_USER_EXTS" : "Recargar sin extensiones", "CMD_NEW_BRACKETS_WINDOW" : "Nueva ventana de {APP_NAME}", "CMD_SWITCH_LANGUAGE" : "Cambiar idioma", "CMD_RUN_UNIT_TESTS" : "Ejecutar tests", "CMD_SHOW_PERF_DATA" : "Mostrar información de rendimiento", "CMD_ENABLE_NODE_DEBUGGER" : "Habilitar depuración de Node", "CMD_LOG_NODE_STATE" : "Mostrar estado de Node en Consola", "CMD_RESTART_NODE" : "Reiniciar Node", "CMD_SHOW_ERRORS_IN_STATUS_BAR" : "Mostrar errores en la barra de estado", "CMD_OPEN_BRACKETS_SOURCE" : "Abrir el código fuente de Brackets", "LANGUAGE_TITLE" : "Cambiar idioma", "LANGUAGE_MESSAGE" : "Idioma:", "LANGUAGE_SUBMIT" : "Reiniciar {APP_NAME}", "LANGUAGE_CANCEL" : "Cancelar", "LANGUAGE_SYSTEM_DEFAULT" : "Idioma predeterminado", // extensions/default/InlineTimingFunctionEditor "INLINE_TIMING_EDITOR_TIME" : "Tiempo", "INLINE_TIMING_EDITOR_PROGRESSION" : "Progresión", "BEZIER_EDITOR_INFO" : "<kbd>↑</kbd><kbd>↓</kbd><kbd>←</kbd><kbd>→</kbd> Mueven el punto seleccionado<br><kbd class='text'>Shift</kbd> Mueve de a diez unidades<br><kbd class='text'>Tab</kbd> Cambia el punto seleccionado", "STEPS_EDITOR_INFO" : "<kbd>↑</kbd><kbd>↓</kbd> Incrementa o disminuya los pasos<br><kbd>←</kbd><kbd>→</kbd> 'Start' o 'End'", "INLINE_TIMING_EDITOR_INVALID" : "El valor viejo <code>{0}</code> no es válido, por lo tanto, fue modificado a <code>{1}</code>. El documento será actualizado luego de la primer edición.", // extensions/default/InlineColorEditor "COLOR_EDITOR_CURRENT_COLOR_SWATCH_TIP" : "Color actual", "COLOR_EDITOR_ORIGINAL_COLOR_SWATCH_TIP" : "Color original", "COLOR_EDITOR_RGBA_BUTTON_TIP" : "Formato RGBa", "COLOR_EDITOR_HEX_BUTTON_TIP" : "Formato Hex", "COLOR_EDITOR_HSLA_BUTTON_TIP" : "Formato HSLa", "COLOR_EDITOR_USED_COLOR_TIP_SINGULAR" : "{0} (Utilizado {1} vez)", "COLOR_EDITOR_USED_COLOR_TIP_PLURAL" : "{0} (Utilizado {1} veces)", // extensions/default/JavaScriptCodeHints "CMD_JUMPTO_DEFINITION" : "Saltar a la definición", "CMD_SHOW_PARAMETER_HINT" : "Mostrar sugerencias de parámetros", "NO_ARGUMENTS" : "<no hay parámetros>", "DETECTED_EXCLUSION_TITLE" : "Problema de inferencia con un archivo JavaScript", "DETECTED_EXCLUSION_INFO" : "Brackets se encontró con problemas procesando: <span class='dialog-filename'>{0}</span>.<br><br>Este archivo no volverá a ser procesado para las sugerencias de código, saltar a la definición o para la edición rápida. Para reactivar este archivo, abra el archivo <code>.brackets.json</code> en su proyecto y edite <code>jscodehints.detectedExclusions</code><br><br>Esto es probablemente un error en Brackets. Si puede proporcionar una copia de este archivo, por favor <a href='https://github.com/adobe/brackets/wiki/How-to-Report-an-Issue'>envíe un informe</a> con un vínculo a dicho archivo.", // extensions/default/JSLint "JSLINT_NAME" : "JSLint", // extensions/default/QuickView "CMD_ENABLE_QUICK_VIEW" : "Vista rápida con cursor", // extensions/default/RecentProjects "CMD_TOGGLE_RECENT_PROJECTS" : "Proyectos recientes", // extensions/default/WebPlatformDocs "DOCS_MORE_LINK" : "Más" }); /* Last translated for c292e896761bc7d451a9e3b95bedd20d6b355d77 */
egghead.io/react_fundamentals/lessons/14-build-compiler/App.js
andrisazens/learning_react
// https://jsbin.com/qonaga/edit?js,output import React from 'react'; class App extends React.Component { constructor(){ super(); this.state = { input: '/* add your jsx here */', output: '', err: '' } this.update = this.update.bind(this); } update(e){ let code = e.target.value; try { this.setState({ output: babel.transform(code, { stage: 0, loose: 'all', comments: true }).code, err: '' }) } catch(err){ this.setState({err: err.message}) } } render(){ return ( <div> <header>{this.state.err}</header> <div className="container"> <textarea onChange={this.update} defaultValue={this.state.input}> </textarea> <pre> {this.state.output} </pre> </div> </div> ) } } export default App
src/svg-icons/file/cloud-upload.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let FileCloudUpload = (props) => ( <SvgIcon {...props}> <path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/> </SvgIcon> ); FileCloudUpload = pure(FileCloudUpload); FileCloudUpload.displayName = 'FileCloudUpload'; FileCloudUpload.muiName = 'SvgIcon'; export default FileCloudUpload;
src/shared/components/signUpLink/signUpLink.js
hollomancer/operationcode_frontend
import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; const SignUpLink = ({ text }) => ( <Link to="/join">{text}</Link> ); SignUpLink.propTypes = { text: PropTypes.string }; SignUpLink.defaultProps = { text: 'Sign up' }; export default SignUpLink;
js/jquery-1.10.2.min.js
adamwong246/github-issue-prioritizer
/*! 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);
app/node_modules/react-router/es6/IndexRedirect.js
lycha/masters-thesis
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import Redirect from './Redirect'; import { falsy } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var object = _React$PropTypes.object; /** * An <IndexRedirect> is used to redirect from an indexRoute. */ var IndexRedirect = React.createClass({ displayName: 'IndexRedirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = Redirect.createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0; } } }, propTypes: { to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRedirect;
src/svg-icons/action/announcement.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAnnouncement = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 9h-2V5h2v6zm0 4h-2v-2h2v2z"/> </SvgIcon> ); ActionAnnouncement = pure(ActionAnnouncement); ActionAnnouncement.displayName = 'ActionAnnouncement'; ActionAnnouncement.muiName = 'SvgIcon'; export default ActionAnnouncement;
src/redux/__mocks__/react-redux.js
yeojz/react-form-addons
import React from 'react'; import noop from 'lodash/noop'; export const connect = (mapStateToProps, mapDispatchToProps) => (Component) => (overrides = {}) => { const stateProps = mapStateToProps({}); const dispatchProps = typeof mapDispatchToProps === 'function' ? mapDispatchToProps(noop) : mapDispatchToProps return function ConnectMock(props) { return <Component {...props} {...stateProps} {...dispatchProps} {...overrides}/> }; }
App/db/entities/Structure/Collection.js
CaipiLabs/caipi
/* * Copyright (c) 2018. Wise Wild Web * * This File is part of Caipi and under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License * Full license at https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode * * @author : Nathanael Braun * @contact : caipilabs@gmail.com */ import React from 'react'; import {types, validate} from "App/db/field/index"; export default { alias : "Collection", label : "Collection", apiRoute : "collection", adminRoute: "Structure/Collections", autoMount : ["items"], // @optional properties that need to be included in a get quuery (format : {objId:(id),_cls:(entity type)}) aliasField: "label", // @optional fields used to generate alias processResult: { "get": function ( record, cuser ) { if ( !record._public ) if ( !cuser || !cuser.isPublisher ) { return null; } return record; } }, schema : { label: [validate.mandatory, validate.noHtml], text : [validate.noJs] }, fields : { "_id" : types.indexes, "_public" : types.boolean("Publier :", false), "label" : types.labels(), "previewImage": types.media({ allowedTypes: "Image" }, "Preview :"), "text" : types.descriptions(), "useLink" : types.boolean("Use links :", false), "items" : types.collection(true, { storeTypedItem : true, allowedUploadTypes: ["Image", "Video"], allowUpload : true }, "Content :") } };
ajax/libs/backbone-react-component/0.6.1/backbone-react-component.js
skidding/cdnjs
// Backbone React Component // ======================== // // Backbone.React.Component v0.6.1 // // (c) 2014 "Magalhas" José Magalhães <magalhas@gmail.com> // Backbone.React.Component can be freely distributed under the MIT license. // // // `Backbone.React.Component` is a React.Component wrapper that serves // as a bridge between the React and Backbone worlds. Besides some extra members // that may be set by extending/instancing a component, it works pretty much the // same way that [React](http://facebook.github.io/react/) components do. // // When mounted (if using mixin mode) or created (wrapper mode) it starts listening // to models and collections changes to automatically set your component props and // achieve UI binding through reactive updates. // // // Basic usage // // var MyComponent = Backbone.React.Component.extend({ // render: function () { // return <div>{this.props.foo}</div>; // } // }); // var model = new Backbone.Model({foo: 'bar'}); // var myComponent = <MyComponent el={document.body} model={model} />; // myComponent.mount(); // // Mixin usage // // var MyComponent = React.createClass({ // mixins: [Backbone.React.Component.mixin], // render: function () { // return <div>{this.props.foo}</div>; // } // }); // var model = new Backbone.Model({foo: 'bar'}); // React.renderComponent(<MyComponent el={document.body} model={model} />, document.body); 'use strict'; (function (root, factory) { // Universal module definition if (typeof define === 'function' && define.amd) define(['react', 'backbone', 'underscore'], factory); else if (typeof module !== 'undefined' && module.exports) { var React = require('react'); var Backbone = require('backbone'); var _ = require('underscore'); module.exports = factory(React, Backbone, _); } else factory(root.React, root.Backbone, root._); }(this, function (React, Backbone, _) { // Here lies the public API available on each component that runs through the wrapper // instead of the mixin approach. if (!Backbone.React) Backbone.React = {}; Backbone.React.Component = { // Wraps `React.Component` into `Backbone.React.Component` and extends to a new // class. extend: function (Clazz) { function Factory (props, children) { return (new Wrapper(Component, props, children)).virtualComponent; } // Allow deep extending Factory.extend = function () { return Backbone.React.Component.extend(_.extend({}, Clazz, arguments[0])); }; // Apply mixin if (Clazz.mixins) { if (Clazz.mixins[0] !== mixin) Clazz.mixins.splice(0, 0, mixin); } else Clazz.mixins = [mixin]; // Create the react component later used by `Factory` var Component = React.createClass(_.extend(Factory.prototype, Clazz)); return Factory; }, // Renders/mounts the component. It delegates to `React.renderComponent`. mount: function (el, onRender) { if (!(el || this.el)) throw new Error('No element to mount on'); else if (!el) el = this.el; this.wrapper.component = React.renderComponent(this, el, onRender); return this; }, // Stops all listeners and unmounts this component from the DOM. remove: function () { if (this.wrapper.component && this.wrapper.component.isMounted()) this.unmount(); this.wrapper.stopListening(); this.stopListening(); }, // Intended to be used on the server side (Node.js), renders your component to a string // ready to be used on the client side by delegating to `React.renderComponentToString`. toHTML: function () { // Since we're only able to call `renderComponentToString` once, lets clone this component // and use it insteaad. var clone = this.clone(_.extend({}, this.props, { collection: this.wrapper.collection, model: this.wrapper.model })); // Return the html representation of the component. return React.renderComponentToString(clone); }, // Unmount the component from the DOM. unmount: function () { var parentNode = this.el.parentNode; if (!React.unmountComponentAtNode(parentNode)) { // Throw an error if there's any unmounting the component. throw new Error('There was an error unmounting the component'); } delete this.wrapper.component; this.setElement(parentNode); } }; // Mixin used in all component instances. Exported through `Backbone.React.Component.mixin`. var mixin = Backbone.React.Component.mixin = { // Sets this.el and this.$el when the component mounts. componentDidMount: function () { this.setElement(this.getDOMNode()); }, // Sets this.el and this.$el when the component updates. componentDidUpdate: function () { this.setElement(this.getDOMNode()); }, // Checks if the component is running in mixin or wrapper mode when it mounts. // If it's a mixin set a flag for later use and instance a Wrapper to take care // of models and collections binding. componentWillMount: function () { if (!this.wrapper) { this.isBackboneMixin = true; this.wrapper = new Wrapper(this, this.props); } }, // If running in mixin mode disposes of the wrapper that was created when the // component mounted. componentWillUnmount: function () { if (this.wrapper && this.isBackboneMixin) { this.wrapper.stopListening(); delete this.wrapper; } }, // Shortcut to this.$el.find. Inspired by Backbone.View. $: function () { if (this.$el) return this.$el.find.apply(this.$el, arguments); }, // Crawls to the owner of the component searching for a collection. getCollection: function () { var owner = this; var lookup = owner.wrapper; while (!lookup.collection) { owner = owner._owner; if (!owner) throw new Error('Collection not found'); lookup = owner.wrapper; } return lookup.collection; }, // Crawls to the owner of the component searching for a model. getModel: function () { var owner = this; var lookup = owner.wrapper; while (!lookup.model) { owner = owner._owner; if (!owner) throw new Error('Model not found'); lookup = owner.wrapper; } return lookup.model; }, // Crawls `this._owner` recursively until it finds the owner of this // component. In case of being a parent component (no owners) it returns itself. getOwner: function () { var owner = this; while (owner._owner) owner = owner._owner; return owner; }, // Sets a DOM element to render/mount this component on this.el and this.$el. setElement: function (el) { if (el && Backbone.$ && el instanceof Backbone.$) { if (el.length > 1) throw new Error('You can only assign one element to a component'); this.el = el[0]; this.$el = el; } else if (el) { this.el = el; if (Backbone.$) this.$el = Backbone.$(el); } return this; } }; // Binds models and collections to a React.Component. It mixes Backbone.Events. function Wrapper (Component, props) { props = props || {}; var el, model = props.model, collection = props.collection; // Check if props.el is a DOM element or a jQuery object if (_.isElement(props.el) || Backbone.$ && props.el instanceof Backbone.$) { el = props.el; delete props.el; } // Check if props.model is a Backbone.Model or an hashmap of them if (typeof model !== 'undefined' && (model.attributes || typeof model === 'object' && _.values(model)[0].attributes)) { delete props.model; // The model(s) bound to this component this.model = model; // Set model(s) attributes on props for the first render this.setPropsBackbone(model, void 0, props); } // Check if props.collection is a Backbone.Collection or an hashmap of them if (typeof collection !== 'undefined' && (collection.models || typeof collection === 'object' && _.values(collection)[0].models)) { delete props.collection; // The collection(s) bound to this component this.collection = collection; // Set collection(s) models on props for the first render this.setPropsBackbone(collection, void 0, props); } var component; if (Component.prototype) { // Instance the component mixing Backbone.Events, our public API and some special // properties. component = this.virtualComponent = _.defaults(Component.apply(this, _.rest(arguments)).__realComponentInstance, Backbone.Events, _.omit(Backbone.React.Component, 'mixin'), { // Clones the component wrapper and returns the component. clone: function (props, children) { return (new Wrapper(Component, props, children)).virtualComponent; }, // Assign a component unique id, this is handy sometimes as a DOM attribute cid: _.uniqueId(), // One to one relationship between the wrapper and the component wrapper: this }); // Set element if (el) mixin.setElement.call(component, el); } else { component = Component; this.component = component; } // Start listeners if this is a root node if (!component._owner) { this.startModelListeners(); this.startCollectionListeners(); } } // Mixing `Backbone.Events` into `Wrapper.prototype` _.extend(Wrapper.prototype, Backbone.Events, { // Sets this.props when a model/collection request results in error. It delegates // to `this.setProps`. It listens to `Backbone.Model#error` and `Backbone.Collection#error`. onError: function (modelOrCollection, res, options) { // Set props only if there's no silent option if (!options.silent) this.setProps({ isRequesting: false, hasError: true, error: res }); }, // Sets this.props when a model/collection request starts. It delegates to // `this.setProps`. It listens to `Backbone.Model#request` and `Backbone.Collection#request`. onRequest: function (modelOrCollection, xhr, options) { // Set props only if there's no silent option if (!options.silent) this.setProps({ isRequesting: true, hasError: false }); }, // Sets this.props when a model/collection syncs. It delegates to `this.setProps`. // It listens to `Backbone.Model#sync` and `Backbone.Collection#sync` onSync: function (modelOrCollection, res, options) { // Set props only if there's no silent option if (!options.silent) this.setProps({isRequesting: false}); }, // Used internally to set this.collection or this.model on this.props. Delegates to // `this.setProps`. It listens to `Backbone.Collection#add`, `Backbone.Collection#remove`, // `Backbone.Collection#change` and `Backbone.Model#change`. setPropsBackbone: function (modelOrCollection, key, target) { if (!(modelOrCollection.models || modelOrCollection.attributes)) { for (key in modelOrCollection) this.setPropsBackbone(modelOrCollection[key], key, target); return; } this.setProps.apply(this, arguments); }, // Sets a model, collection or object into props by delegating to `React.Component#setProps`. setProps: function (modelOrCollection, key, target) { // If the component isn't rendered/mounted set target because you can't set props // on an unmounted (virtual) component. if (!target && !(this.component && this.component.isMounted())) target = this.virtualComponent.props; var props = {}; var newProps = modelOrCollection.toJSON ? modelOrCollection.toJSON() : modelOrCollection; if (key) props[key] = newProps; else if (modelOrCollection instanceof Backbone.Collection) props.collection = newProps; else props = newProps; if (target) _.extend(target, props); else { this.nextProps = _.extend(this.nextProps || {}, props); _.defer(_.bind(function () { if (this.nextProps) { this.component.setProps(this.nextProps); delete this.nextProps; } }, this)); } }, // Binds the component to any collection changes. startCollectionListeners: function (collection, key) { if (!collection) collection = this.collection; if (collection) { if (collection.models) this .listenTo(collection, 'add remove change sort', _.partial(this.setPropsBackbone, collection, key, void 0)) .listenTo(collection, 'error', this.onError) .listenTo(collection, 'request', this.onRequest) .listenTo(collection, 'sync', this.onSync); else if (typeof collection === 'object') for (key in collection) if (collection.hasOwnProperty(key)) this.startCollectionListeners(collection[key], key); } }, // Binds the component to any model changes. startModelListeners: function (model, key) { if (!model) model = this.model; if (model) { if (model.attributes) this .listenTo(model, 'change', _.partial(this.setPropsBackbone, model, key, void 0)) .listenTo(model, 'error', this.onError) .listenTo(model, 'request', this.onRequest) .listenTo(model, 'sync', this.onSync); else if (typeof model === 'object') for (key in model) this.startModelListeners(model[key], key); } } }); // Expose `Backbone.React.Component`. return Backbone.React.Component; })); // <a href="https://github.com/magalhas/backbone-react-component"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://github-camo.global.ssl.fastly.net/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
test/markup-frame-test.js
sirbrillig/markup-frame
import React from 'react'; import ReactDOM from 'react-dom'; import { expect } from 'chai'; import MarkupFrame from '../src'; function mount( component ) { const contentArea = window.document.querySelector( '#content' ); ReactDOM.render( component, contentArea ); } describe( '<MarkupFrame />', function() { it( 'renders an iframe', function() { mount( <MarkupFrame markup="" /> ); const iframes = window.document.querySelectorAll( 'iframe' ); expect( iframes ).to.have.length( 1 ); } ); it( 'injects props.markup into the iframe', function() { mount( <MarkupFrame markup="<h1>Hello World</h1>" /> ); const iframe = window.document.querySelector( 'iframe' ); expect( iframe.contentWindow.document.body.innerHTML ).to.eql( '<h1>Hello World</h1>' ) } ); it.skip( 'calls props.onLoad with the iframe document', function( done ) { const onLoad = function( doc ) { doc.querySelector( 'h1' ).innerHTML = 'greetings'; const iframe = window.document.querySelector( 'iframe' ); expect( iframe.contentWindow.document.body.innerHTML ).to.eql( '<h1>greetings</h1>' ); done(); }; mount( <MarkupFrame markup="<h1>Hello World</h1>" onLoad={ onLoad } /> ); } ); } );
examples/counter/containers/CounterApp.js
andrew-codes/redux
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'redux/react'; import Counter from '../components/Counter'; import * as CounterActions from '../actions/CounterActions'; @connect(state => ({ counter: state.counter })) export default class CounterApp extends Component { render() { const { counter, dispatch } = this.props; return ( <Counter counter={counter} {...bindActionCreators(CounterActions, dispatch)} /> ); } }
wp-content/plugins/myplugin/resource_popular/res/jquery-validation-1.13.1/lib/jquery-1.8.3.js
phanngoc/cosomassage
/*! * jQuery JavaScript Library v1.8.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time) */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.3", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) return (cache[ key + " " ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem, context ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "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 ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // 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 )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( e ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
files/videojs/5.0.0-rc.31/video.js
wallin/jsdelivr
/** * @license * Video.js 5.0.0-rc.31 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> * * Includes vtt.js <https://github.com/mozilla/vtt.js> * Available under Apache License Version 2.0 * <https://github.com/mozilla/vtt.js/blob/master/LICENSE> */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = _dereq_('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"min-document":3}],2:[function(_dereq_,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],3:[function(_dereq_,module,exports){ },{}],4:[function(_dereq_,module,exports){ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; },{}],5:[function(_dereq_,module,exports){ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = arrayCopy; },{}],6:[function(_dereq_,module,exports){ /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; },{}],7:[function(_dereq_,module,exports){ /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } module.exports = baseCopy; },{}],8:[function(_dereq_,module,exports){ var createBaseFor = _dereq_('./createBaseFor'); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; },{"./createBaseFor":17}],9:[function(_dereq_,module,exports){ var baseFor = _dereq_('./baseFor'), keysIn = _dereq_('../object/keysIn'); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } module.exports = baseForIn; },{"../object/keysIn":39,"./baseFor":8}],10:[function(_dereq_,module,exports){ /** * The base implementation of `_.isFunction` without support for environments * with incorrect `typeof` results. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. */ function baseIsFunction(value) { // Avoid a Chakra JIT bug in compatibility modes of IE 11. // See https://github.com/jashkenas/underscore/issues/1621 for more details. return typeof value == 'function' || false; } module.exports = baseIsFunction; },{}],11:[function(_dereq_,module,exports){ var arrayEach = _dereq_('./arrayEach'), baseMergeDeep = _dereq_('./baseMergeDeep'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isObject = _dereq_('../lang/isObject'), isObjectLike = _dereq_('./isObjectLike'), isTypedArray = _dereq_('../lang/isTypedArray'), keys = _dereq_('../object/keys'); /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? null : keys(source); arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((result !== undefined || (isSrcArr && !(key in object))) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } module.exports = baseMerge; },{"../lang/isArray":30,"../lang/isObject":33,"../lang/isTypedArray":36,"../object/keys":38,"./arrayEach":6,"./baseMergeDeep":12,"./isArrayLike":20,"./isObjectLike":25}],12:[function(_dereq_,module,exports){ var arrayCopy = _dereq_('./arrayCopy'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isPlainObject = _dereq_('../lang/isPlainObject'), isTypedArray = _dereq_('../lang/isTypedArray'), toPlainObject = _dereq_('../lang/toPlainObject'); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (isArrayLike(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } module.exports = baseMergeDeep; },{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isPlainObject":34,"../lang/isTypedArray":36,"../lang/toPlainObject":37,"./arrayCopy":5,"./isArrayLike":20}],13:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : toObject(object)[key]; }; } module.exports = baseProperty; },{"./toObject":28}],14:[function(_dereq_,module,exports){ /** * Converts `value` to a string if it's not one. An empty string is returned * for `null` or `undefined` values. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } module.exports = baseToString; },{}],15:[function(_dereq_,module,exports){ var identity = _dereq_('../utility/identity'); /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } module.exports = bindCallback; },{"../utility/identity":43}],16:[function(_dereq_,module,exports){ var bindCallback = _dereq_('./bindCallback'), isIterateeCall = _dereq_('./isIterateeCall'), restParam = _dereq_('../function/restParam'); /** * Creates a function that assigns properties of source object(s) to a given * destination object. * * **Note:** This function is used to create `_.assign`, `_.defaults`, and `_.merge`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : undefined; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner; },{"../function/restParam":4,"./bindCallback":15,"./isIterateeCall":23}],17:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; },{"./toObject":28}],18:[function(_dereq_,module,exports){ var baseProperty = _dereq_('./baseProperty'); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; },{"./baseProperty":13}],19:[function(_dereq_,module,exports){ var isNative = _dereq_('../lang/isNative'); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; },{"../lang/isNative":32}],20:[function(_dereq_,module,exports){ var getLength = _dereq_('./getLength'), isLength = _dereq_('./isLength'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } module.exports = isArrayLike; },{"./getLength":18,"./isLength":24}],21:[function(_dereq_,module,exports){ /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { // IE < 9 presents many host objects as `Object` objects that can coerce // to strings despite having improperly defined `toString` methods. return typeof value.toString != 'function' && typeof (value + '') == 'string'; }; }()); module.exports = isHostObject; },{}],22:[function(_dereq_,module,exports){ /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; },{}],23:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('./isArrayLike'), isIndex = _dereq_('./isIndex'), isObject = _dereq_('../lang/isObject'); /** * Checks if the provided arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object)) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } module.exports = isIterateeCall; },{"../lang/isObject":33,"./isArrayLike":20,"./isIndex":22}],24:[function(_dereq_,module,exports){ /** * Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; },{}],25:[function(_dereq_,module,exports){ /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; },{}],26:[function(_dereq_,module,exports){ var baseForIn = _dereq_('./baseForIn'), isArguments = _dereq_('../lang/isArguments'), isHostObject = _dereq_('./isHostObject'), isObjectLike = _dereq_('./isObjectLike'), support = _dereq_('../support'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * A fallback implementation of `_.isPlainObject` which checks if `value` * is an object created by the `Object` constructor or has a `[[Prototype]]` * of `null`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { var Ctor; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value)) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor))) || (!support.argsTag && isArguments(value))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; if (support.ownLast) { baseForIn(value, function(subValue, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result !== false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } module.exports = shimIsPlainObject; },{"../lang/isArguments":29,"../support":42,"./baseForIn":9,"./isHostObject":21,"./isObjectLike":25}],27:[function(_dereq_,module,exports){ var isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isIndex = _dereq_('./isIndex'), isLength = _dereq_('./isLength'), isString = _dereq_('../lang/isString'), keysIn = _dereq_('../object/keysIn'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; },{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isString":35,"../object/keysIn":39,"./isIndex":22,"./isLength":24}],28:[function(_dereq_,module,exports){ var isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { if (support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); } module.exports = toObject; },{"../lang/isObject":33,"../lang/isString":35,"../support":42}],29:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('../internal/isArrayLike'), isObjectLike = _dereq_('../internal/isObjectLike'), support = _dereq_('../support'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && objToString.call(value) == argsTag; } // Fallback for environments without a `toStringTag` for `arguments` objects. if (!support.argsTag) { isArguments = function(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; } module.exports = isArguments; },{"../internal/isArrayLike":20,"../internal/isObjectLike":25,"../support":42}],30:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; module.exports = isArray; },{"../internal/getNative":19,"../internal/isLength":24,"../internal/isObjectLike":25}],31:[function(_dereq_,module,exports){ (function (global){ var baseIsFunction = _dereq_('../internal/baseIsFunction'), getNative = _dereq_('../internal/getNative'); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Native method references. */ var Uint8Array = getNative(global, 'Uint8Array'); /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 equivalents which return 'object' for typed array constructors. return objToString.call(value) == funcTag; }; module.exports = isFunction; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../internal/baseIsFunction":10,"../internal/getNative":19}],32:[function(_dereq_,module,exports){ var escapeRegExp = _dereq_('../string/escapeRegExp'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + escapeRegExp(fnToString.call(hasOwnProperty)) .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } module.exports = isNative; },{"../internal/isHostObject":21,"../internal/isObjectLike":25,"../string/escapeRegExp":41}],33:[function(_dereq_,module,exports){ /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; },{}],34:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isArguments = _dereq_('./isArguments'), shimIsPlainObject = _dereq_('../internal/shimIsPlainObject'), support = _dereq_('../support'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Native method references. */ var getPrototypeOf = getNative(Object, 'getPrototypeOf'); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && objToString.call(value) == objectTag) || (!support.argsTag && isArguments(value))) { return false; } var valueOf = getNative(value, 'valueOf'), objProto = valueOf && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; module.exports = isPlainObject; },{"../internal/getNative":19,"../internal/shimIsPlainObject":26,"../support":42,"./isArguments":29}],35:[function(_dereq_,module,exports){ var isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } module.exports = isString; },{"../internal/isObjectLike":25}],36:[function(_dereq_,module,exports){ var isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; },{"../internal/isLength":24,"../internal/isObjectLike":25}],37:[function(_dereq_,module,exports){ var baseCopy = _dereq_('../internal/baseCopy'), keysIn = _dereq_('../object/keysIn'); /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } module.exports = toPlainObject; },{"../internal/baseCopy":7,"../object/keysIn":39}],38:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isArrayLike = _dereq_('../internal/isArrayLike'), isObject = _dereq_('../lang/isObject'), shimKeys = _dereq_('../internal/shimKeys'), support = _dereq_('../support'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? null : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; },{"../internal/getNative":19,"../internal/isArrayLike":20,"../internal/shimKeys":27,"../lang/isObject":33,"../support":42}],39:[function(_dereq_,module,exports){ var arrayEach = _dereq_('../internal/arrayEach'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isFunction = _dereq_('../lang/isFunction'), isIndex = _dereq_('../internal/isIndex'), isLength = _dereq_('../internal/isLength'), isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** `Object#toString` result references. */ var arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** Used to fix the JScript `[[DontEnum]]` bug. */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used for native method references. */ var errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to avoid iterating over non-enumerable properties in IE < 9. */ var nonEnumProps = {}; nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; nonEnumProps[objectTag] = { 'constructor': true }; arrayEach(shadowProps, function(key) { for (var tag in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, tag)) { var props = nonEnumProps[tag]; props[key] = hasOwnProperty.call(props, key); } } }); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)) && length) || 0; var Ctor = object.constructor, index = -1, proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, isProto = proto === object, result = Array(length), skipIndexes = length > 0, skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), skipProto = support.enumPrototypes && isFunction(object); while (++index < length) { result[index] = (index + ''); } // lodash skips the `constructor` property when it infers it is iterating // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` // attribute of an existing property and the `constructor` property of a // prototype defaults to non-enumerable. for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name')) && !(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; if (tag == objectTag) { proto = objectProto; } length = shadowProps.length; while (length--) { key = shadowProps[length]; var nonEnum = nonEnums[key]; if (!(isProto && nonEnum) && (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { result.push(key); } } } return result; } module.exports = keysIn; },{"../internal/arrayEach":6,"../internal/isIndex":22,"../internal/isLength":24,"../lang/isArguments":29,"../lang/isArray":30,"../lang/isFunction":31,"../lang/isObject":33,"../lang/isString":35,"../support":42}],40:[function(_dereq_,module,exports){ var baseMerge = _dereq_('../internal/baseMerge'), createAssigner = _dereq_('../internal/createAssigner'); /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it is invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); module.exports = merge; },{"../internal/baseMerge":11,"../internal/createAssigner":16}],41:[function(_dereq_,module,exports){ var baseToString = _dereq_('../internal/baseToString'); /** * Used to match `RegExp` [special characters](http://www.regular-expressions.info/characters.html#special). * In addition to special characters the forward slash is escaped to allow for * easier `eval` use and `Function` compilation. */ var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); /** * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. * * @static * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' */ function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } module.exports = escapeRegExp; },{"../internal/baseToString":14}],42:[function(_dereq_,module,exports){ (function (global){ /** `Object#toString` result references. */ var argsTag = '[object Arguments]', objectTag = '[object Object]'; /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, objectProto = Object.prototype; /** Used to detect DOM support. */ var document = (document = global.window) ? document.document : null; /** * Used to resolve the [`toStringTag`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if the `toStringTag` of `arguments` objects is resolvable * (all but Firefox < 4, IE < 9). * * @memberOf _.support * @type boolean */ support.argsTag = objToString.call(arguments) == argsTag; /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default (IE < 9, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly set the `[[Enumerable]]` value of a function's `prototype` * property to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); /** * Detect if the `toStringTag` of DOM nodes is resolvable (all but IE < 9). * * @memberOf _.support * @type boolean */ support.nodeTag = objToString.call(document) != objectTag; /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an object's own properties, shadowing non-enumerable ones, * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects * correctly. * * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array * `shift()` and `splice()` functions that fail to remove the last element, * `value[0]`, of array-like objects even though the "length" property is * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, * while `splice()` is buggy regardless of mode in IE < 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index. IE 8 can only access characters * by index on string literals, not string objects. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; /** * Detect if the DOM is supported. * * @memberOf _.support * @type boolean */ try { support.dom = document.createDocumentFragment().nodeType === 11; } catch(e) { support.dom = false; } }(1, 0)); module.exports = support; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],43:[function(_dereq_,module,exports){ /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; },{}],44:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es6-shim var keys = _dereq_('object-keys'); var canBeObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var defineProperties = _dereq_('define-properties'); var propIsEnumerable = Object.prototype.propertyIsEnumerable; var isEnumerableOn = function (obj) { return function isEnumerable(prop) { return propIsEnumerable.call(obj, prop); }; }; var assignShim = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } var objTarget = Object(target); var s, source, i, props; for (s = 1; s < arguments.length; ++s) { source = Object(arguments[s]); props = keys(source); if (hasSymbols && Object.getOwnPropertySymbols) { props.push.apply(props, Object.getOwnPropertySymbols(source).filter(isEnumerableOn(source))); } for (i = 0; i < props.length; ++i) { objTarget[props[i]] = source[props[i]]; } } return objTarget; }; assignShim.shim = function shimObjectAssign() { if (Object.assign && Object.preventExtensions) { var assignHasPendingExceptions = (function () { // Firefox 37 still has "pending exception" logic in its Object.assign implementation, // which is 72% slower than our shim, and Firefox 40's native implementation. var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } }()); if (assignHasPendingExceptions) { delete Object.assign; } } if (!Object.assign) { defineProperties(Object, { assign: assignShim }); } return Object.assign || assignShim; }; module.exports = assignShim; },{"define-properties":45,"object-keys":47}],45:[function(_dereq_,module,exports){ 'use strict'; var keys = _dereq_('object-keys'); var foreach = _dereq_('foreach'); var toStr = Object.prototype.toString; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { value: obj }); return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; foreach(keys(map), function (name) { defineProperty(object, name, map[name], predicates[name]); }); }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; },{"foreach":46,"object-keys":47}],46:[function(_dereq_,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; },{}],47:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArgs = _dereq_('./isArguments'); var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString'); var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var ctor = object.constructor; var skipConstructor = ctor && ctor.prototype === object; for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (!Object.keys) { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; },{"./isArguments":48}],48:[function(_dereq_,module,exports){ 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; },{}],49:[function(_dereq_,module,exports){ module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } },{}],50:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file big-play-button.js */ var _Button2 = _dereq_('./button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('./component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Button * @class BigPlayButton */ var BigPlayButton = (function (_Button) { function BigPlayButton(player, options) { _classCallCheck(this, BigPlayButton); _Button.call(this, player, options); } _inherits(BigPlayButton, _Button); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ BigPlayButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; }; /** * Handles click for play * * @method handleClick */ BigPlayButton.prototype.handleClick = function handleClick() { this.player_.play(); }; return BigPlayButton; })(_Button3['default']); BigPlayButton.prototype.controlText_ = 'Play Video'; _Component2['default'].registerComponent('BigPlayButton', BigPlayButton); exports['default'] = BigPlayButton; module.exports = exports['default']; },{"./button.js":51,"./component.js":52}],51:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file button.js */ var _Component2 = _dereq_('./component'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import2); var _import3 = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import3); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); /** * Base class for all buttons * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class Button */ var Button = (function (_Component) { function Button(player, options) { _classCallCheck(this, Button); _Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.handleClick); this.on('click', this.handleClick); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); } _inherits(Button, _Component); /** * Create the component's DOM element * * @param {String=} type Element's node type. e.g. 'div' * @param {Object=} props An object of element attributes that should be set on the element Tag name * @return {Element} * @method createEl */ Button.prototype.createEl = function createEl() { var type = arguments[0] === undefined ? 'button' : arguments[0]; var props = arguments[1] === undefined ? {} : arguments[1]; // Add standard Aria and Tabindex info props = _assign2['default']({ className: this.buildCSSClass(), role: 'button', 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); var el = _Component.prototype.createEl.call(this, type, props); this.controlTextEl_ = Dom.createEl('span', { className: 'vjs-control-text' }); el.appendChild(this.controlTextEl_); this.controlText(this.controlText_); return el; }; /** * Controls text - both request and localize * * @param {String} text Text for button * @return {String} * @method controlText */ Button.prototype.controlText = function controlText(text) { if (!text) { return this.controlText_ || 'Need Text'; }this.controlText_ = text; this.controlTextEl_.innerHTML = this.localize(this.controlText_); return this; }; /** * Allows sub components to stack CSS class names * * @return {String} * @method buildCSSClass */ Button.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handle Click - Override with specific functionality for button * * @method handleClick */ Button.prototype.handleClick = function handleClick() {}; /** * Handle Focus - Add keyboard functionality to element * * @method handleFocus */ Button.prototype.handleFocus = function handleFocus() { Events.on(_document2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; /** * Handle KeyPress (document level) - Trigger click when keys are pressed * * @method handleKeyPress */ Button.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleClick(); } }; /** * Handle Blur - Remove keyboard triggers * * @method handleBlur */ Button.prototype.handleBlur = function handleBlur() { Events.off(_document2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; return Button; })(_Component3['default']); _Component3['default'].registerComponent('Button', Button); exports['default'] = Button; module.exports = exports['default']; },{"./component":52,"./utils/dom.js":110,"./utils/events.js":111,"./utils/fn.js":112,"global/document":1,"object.assign":44}],52:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; exports.__esModule = true; /** * @file component.js * * Player Component - Base class for all UI objects */ var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _import = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _import3 = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_import3); var _import4 = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import4); var _log = _dereq_('./utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _toTitleCase = _dereq_('./utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var _mergeOptions = _dereq_('./utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); /** * Base UI Component class * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * ```js * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * ``` * ```html * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * ``` * Components are also event emitters. * ```js * button.on('click', function(){ * console.log('Button Clicked!'); * }); * button.trigger('customevent'); * ``` * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @class Component */ var Component = (function () { function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = _mergeOptions2['default']({}, this.options_); // Updated options with supplied options options = this.options_ = _mergeOptions2['default'](this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = '' + id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } // Temp for ES6 class transition, remove before 5.0 Component.prototype.init = function init() { // console.log('init called on Component'); Component.apply(this, arguments); }; /** * Dispose of the component and all child components * * @method dispose */ Component.prototype.dispose = function dispose() { this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } Dom.removeElData(this.el_); this.el_ = null; }; /** * Return the component's player * * @return {Player} * @method player */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects * Whenever a property is an object on both options objects * the two properties will be merged using mergeOptions. * This is used for merging options for child components. We * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * ```js * Parent.prototype.options_ = { * children: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * children: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * ``` * RESULT * ```js * { * children: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * ``` * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged * @method options */ Component.prototype.options = function options(obj) { _log2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = _mergeOptions2['default'](this.options_, obj); return this.options_; }; /** * Get the component's DOM element * ```js * var domEl = myComponent.el(); * ``` * * @return {Element} * @method el */ Component.prototype.el = function el() { return this.el_; }; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} attributes An object of element attributes that should be set on the element * @return {Element} * @method createEl */ Component.prototype.createEl = function createEl(tagName, attributes) { return Dom.createEl(tagName, attributes); }; Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the component's DOM element where children are inserted. * Will either be the same as el() or a new element defined in createEl(). * * @return {Element} * @method contentEl */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get the component's ID * ```js * var id = myComponent.id(); * ``` * * @return {String} * @method id */ Component.prototype.id = function id() { return this.id_; }; /** * Get the component's name. The name is often used to reference the component. * ```js * var name = myComponent.name(); * ``` * * @return {String} * @method name */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * ```js * var kids = myComponent.children(); * ``` * * @return {Array} The children * @method children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns a child component with the provided ID * * @return {Component} * @method getChildById */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns a child component with the provided name * * @return {Component} * @method getChild */ Component.prototype.getChild = function getChild(name) { return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * ```js * myComponent.el(); * // -> <div class='my-component'></div> * myComponent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComonent.children()[0]; * ``` * Pass in options for child constructors and options for children of the child * ```js * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * ``` * * @param {String|Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {Component} The child component (created by this process if a string was used) * @method addChild */ Component.prototype.addChild = function addChild(child) { var options = arguments[1] === undefined ? {} : arguments[1]; var component = undefined; var componentName = undefined; // If child is a string, create nt with options if (typeof child === 'string') { componentName = child; // Options can also be specified as a boolean, so convert to an empty object if false. if (!options) { options = {}; } // Same as above, but true is deprecated so show a warning. if (options === true) { _log2['default'].warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.'); options = {}; } // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) var componentClassName = options.componentClass || _toTitleCase2['default'](componentName); // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && component.name(); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { this.contentEl().appendChild(component.el()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {Component} component Component to remove * @method removeChild */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * ```js * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_.children = { * myChildComponent: { * myChildOption: true * } * } * ``` * // Or when creating the component * ```js * var myComp = new MyComponent(player, { * children: { * myChildComponent: { * myChildOption: true * } * } * }); * ``` * The children option can also be an Array of child names or * child options objects (that also include a 'name' key). * ```js * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * } * ] * }); * ``` * * @method initChildren */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { (function () { // `this` is `parent` var parentOptions = _this.options_; var handleAdd = function handleAdd(name, opts) { // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // We also want to pass the original player options to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each _this[name] = _this.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var child = children[i]; var _name = undefined; var opts = undefined; if (typeof child === 'string') { // ['myComponent'] _name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] _name = child.name; opts = child; } handleAdd(_name, opts); } } else { Object.getOwnPropertyNames(children).forEach(function (name) { handleAdd(name, children[name]); }); } })(); } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Add an event listener to this component's element * ```js * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * ``` * The context of myFunc will be myComponent unless previously bound. * Alternatively, you can add a listener to another element or component. * ```js * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * ``` * The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `myComponent.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {Component} * @method on */ Component.prototype.on = function on(first, second, third) { var _this2 = this; if (typeof first === 'string' || Array.isArray(first)) { Events.on(this.el_, first, Fn.bind(this, second)); // Targeting another component or element } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this2, third); // When this component is disposed, remove the listener from the other component var removeOnDispose = function removeOnDispose() { return _this2.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; _this2.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. var cleanRemover = function cleanRemover() { return _this2.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element Events.on(target, type, fn); Events.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } })(); } return this; }; /** * Remove an event listener from this component's element * ```js * myComponent.off('eventType', myFunc); * ``` * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * ```js * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * ``` * * @param {String=|Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {Component} * @method off */ Component.prototype.off = function off(first, second, third) { if (!first || typeof first === 'string' || Array.isArray(first)) { Events.off(this.el_, first, second); } else { var target = first; var type = second; // Ensure there's at least a guid, even if the function hasn't been used var fn = Fn.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener Events.off(target, type, fn); // Remove the listener for cleaning the dispose listener Events.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * ```js * myComponent.one('eventName', myFunc); * ``` * Alternatively you can add a listener to another element or component * that will be triggered only once. * ```js * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * ``` * * @param {String|Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {Component} * @method one */ Component.prototype.one = function one(first, second, third) { var _this3 = this; var _arguments = arguments; if (typeof first === 'string' || Array.isArray(first)) { Events.one(this.el_, first, Fn.bind(this, second)); } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this3, third); var newFunc = (function (_newFunc) { function newFunc() { return _newFunc.apply(this, arguments); } newFunc.toString = function () { return _newFunc.toString(); }; return newFunc; })(function () { _this3.off(target, type, newFunc); fn.apply(null, _arguments); }); // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; _this3.on(target, type, newFunc); })(); } return this; }; /** * Trigger an event on an element * ```js * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * myComponent.trigger('eventName', {data: 'some data'}); * myComponent.trigger({'type':'eventName'}, {data: 'some data'}); * ``` * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Component} self * @method trigger */ Component.prototype.trigger = function trigger(event, hash) { Events.trigger(this.el_, event, hash); return this; }; /** * Bind a listener to the component's ready state. * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @return {Component} * @method ready */ Component.prototype.ready = function ready(fn) { if (fn) { if (this.isReady_) { // Ensure function is always called asynchronously this.setTimeout(fn, 1); } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {Component} * @method triggerReady */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); // Reset Ready Queue this.readyQueue_ = []; } // Allow for using event listeners also this.trigger('ready'); }, 1); }; /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {Component} * @method hasClass */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasElClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {Component} * @method addClass */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addElClass(this.el_, classToAdd); return this; }; /** * Remove and return a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {Component} * @method removeClass */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeElClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {Component} * @method show */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); return this; }; /** * Hide the component element if currently showing * * @return {Component} * @method hide */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method lockShowing */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method unlockShowing */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); return this; }; /** * Set or get the width of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {Component} This component, when setting the width * @return {Number|String} The width, when getting * @method width */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {Component} This component, when setting the height * @return {Number|String} The height, when getting * @method height */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width Width of player * @param {Number|String} height Height of player * @return {Component} The component * @method dimensions */ Component.prototype.dimensions = function dimensions(width, height) { // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private * @method dimension */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + _toTitleCase2['default'](widthOrHeight)], 10); }; /** * Emit 'tap' events when touch events are supported * This is used to support toggling the controls through a tap on the video. * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * * @private * @method emitTapEvents */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = undefined; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy the touches object to prevent modifying the original firstTouch = _assign2['default']({}, event.touches[0]); // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. * * @method enableTouchActivity */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = undefined; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID * @method setTimeout */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = _window2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID * @method clearTimeout */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _window2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID * @method setInterval */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _window2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID * @method clearInterval */ Component.prototype.clearInterval = function clearInterval(intervalId) { _window2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Registers a component * * @param {String} name Name of the component to register * @param {Object} comp The component to register * @static * @method registerComponent */ Component.registerComponent = function registerComponent(name, comp) { if (!Component.components_) { Component.components_ = {}; } Component.components_[name] = comp; return comp; }; /** * Gets a component by name * * @param {String} name Name of the component to get * @return {Component} * @static * @method getComponent */ Component.getComponent = function getComponent(name) { if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } if (_window2['default'] && _window2['default'].videojs && _window2['default'].videojs[name]) { _log2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)'); return _window2['default'].videojs[name]; } }; /** * Sets up the constructor using the supplied init method * or uses the init of the parent object * * @param {Object} props An object of properties * @static * @deprecated * @method extend */ Component.extend = function extend(props) { props = props || {}; _log2['default'].warn('Component.extend({}) has been deprecated, use videojs.extends(Component, {}) instead'); // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. var subObj = function subObj() { init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = Object.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = Component.extend; // Extend subObj's prototype with functions and other properties from props for (var _name2 in props) { if (props.hasOwnProperty(_name2)) { subObj.prototype[_name2] = props[_name2]; } } return subObj; }; return Component; })(); Component.registerComponent('Component', Component); exports['default'] = Component; module.exports = exports['default']; },{"./utils/dom.js":110,"./utils/events.js":111,"./utils/fn.js":112,"./utils/guid.js":114,"./utils/log.js":115,"./utils/merge-options.js":116,"./utils/to-title-case.js":119,"global/window":2,"object.assign":44}],53:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file control-bar.js */ var _Component2 = _dereq_('../component.js'); var _Component3 = _interopRequireWildcard(_Component2); // Required children var _PlayToggle = _dereq_('./play-toggle.js'); var _PlayToggle2 = _interopRequireWildcard(_PlayToggle); var _CurrentTimeDisplay = _dereq_('./time-controls/current-time-display.js'); var _CurrentTimeDisplay2 = _interopRequireWildcard(_CurrentTimeDisplay); var _DurationDisplay = _dereq_('./time-controls/duration-display.js'); var _DurationDisplay2 = _interopRequireWildcard(_DurationDisplay); var _TimeDivider = _dereq_('./time-controls/time-divider.js'); var _TimeDivider2 = _interopRequireWildcard(_TimeDivider); var _RemainingTimeDisplay = _dereq_('./time-controls/remaining-time-display.js'); var _RemainingTimeDisplay2 = _interopRequireWildcard(_RemainingTimeDisplay); var _LiveDisplay = _dereq_('./live-display.js'); var _LiveDisplay2 = _interopRequireWildcard(_LiveDisplay); var _ProgressControl = _dereq_('./progress-control/progress-control.js'); var _ProgressControl2 = _interopRequireWildcard(_ProgressControl); var _FullscreenToggle = _dereq_('./fullscreen-toggle.js'); var _FullscreenToggle2 = _interopRequireWildcard(_FullscreenToggle); var _VolumeControl = _dereq_('./volume-control/volume-control.js'); var _VolumeControl2 = _interopRequireWildcard(_VolumeControl); var _VolumeMenuButton = _dereq_('./volume-menu-button.js'); var _VolumeMenuButton2 = _interopRequireWildcard(_VolumeMenuButton); var _MuteToggle = _dereq_('./mute-toggle.js'); var _MuteToggle2 = _interopRequireWildcard(_MuteToggle); var _ChaptersButton = _dereq_('./text-track-controls/chapters-button.js'); var _ChaptersButton2 = _interopRequireWildcard(_ChaptersButton); var _SubtitlesButton = _dereq_('./text-track-controls/subtitles-button.js'); var _SubtitlesButton2 = _interopRequireWildcard(_SubtitlesButton); var _CaptionsButton = _dereq_('./text-track-controls/captions-button.js'); var _CaptionsButton2 = _interopRequireWildcard(_CaptionsButton); var _PlaybackRateMenuButton = _dereq_('./playback-rate-menu/playback-rate-menu-button.js'); var _PlaybackRateMenuButton2 = _interopRequireWildcard(_PlaybackRateMenuButton); var _CustomControlSpacer = _dereq_('./spacer-controls/custom-control-spacer.js'); var _CustomControlSpacer2 = _interopRequireWildcard(_CustomControlSpacer); /** * Container of main controls * * @extends Component * @class ControlBar */ var ControlBar = (function (_Component) { function ControlBar() { _classCallCheck(this, ControlBar); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(ControlBar, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ ControlBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar' }); }; return ControlBar; })(_Component3['default']); ControlBar.prototype.options_ = { loadEvent: 'play', children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'muteToggle', 'volumeControl', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle'] }; _Component3['default'].registerComponent('ControlBar', ControlBar); exports['default'] = ControlBar; module.exports = exports['default']; },{"../component.js":52,"./fullscreen-toggle.js":54,"./live-display.js":55,"./mute-toggle.js":56,"./play-toggle.js":57,"./playback-rate-menu/playback-rate-menu-button.js":58,"./progress-control/progress-control.js":62,"./spacer-controls/custom-control-spacer.js":64,"./text-track-controls/captions-button.js":67,"./text-track-controls/chapters-button.js":68,"./text-track-controls/subtitles-button.js":71,"./time-controls/current-time-display.js":74,"./time-controls/duration-display.js":75,"./time-controls/remaining-time-display.js":76,"./time-controls/time-divider.js":77,"./volume-control/volume-control.js":79,"./volume-menu-button.js":81}],54:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file fullscreen-toggle.js */ var _Button2 = _dereq_('../button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * Toggle fullscreen video * * @extends Button * @class FullscreenToggle */ var FullscreenToggle = (function (_Button) { function FullscreenToggle() { _classCallCheck(this, FullscreenToggle); if (_Button != null) { _Button.apply(this, arguments); } } _inherits(FullscreenToggle, _Button); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handles click for full screen * * @method handleClick */ FullscreenToggle.prototype.handleClick = function handleClick() { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText('Fullscreen'); } }; return FullscreenToggle; })(_Button3['default']); FullscreenToggle.prototype.controlText_ = 'Fullscreen'; _Component2['default'].registerComponent('FullscreenToggle', FullscreenToggle); exports['default'] = FullscreenToggle; module.exports = exports['default']; },{"../button.js":51,"../component.js":52}],55:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file live-display.js */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * Displays the live indicator * TODO - Future make it click to snap to live * * @extends Component * @class LiveDisplay */ var LiveDisplay = (function (_Component) { function LiveDisplay() { _classCallCheck(this, LiveDisplay); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(LiveDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ LiveDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'), 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; return LiveDisplay; })(_Component3['default']); _Component3['default'].registerComponent('LiveDisplay', LiveDisplay); exports['default'] = LiveDisplay; module.exports = exports['default']; },{"../component":52,"../utils/dom.js":110}],56:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file mute-toggle.js */ var _Button2 = _dereq_('../button'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * A button component for muting the audio * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MuteToggle */ var MuteToggle = (function (_Button) { function MuteToggle(player, options) { _classCallCheck(this, MuteToggle); _Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } _inherits(MuteToggle, _Button); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MuteToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click on mute * * @method handleClick */ MuteToggle.prototype.handleClick = function handleClick() { this.player_.muted(this.player_.muted() ? false : true); }; /** * Update volume * * @method update */ MuteToggle.prototype.update = function update() { var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. var toMute = this.player_.muted() ? 'Unmute' : 'Mute'; var localizedMute = this.localize(toMute); if (this.controlText() !== localizedMute) { this.controlText(localizedMute); } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { Dom.removeElClass(this.el_, 'vjs-vol-' + i); } Dom.addElClass(this.el_, 'vjs-vol-' + level); }; return MuteToggle; })(_Button3['default']); MuteToggle.prototype.controlText_ = 'Mute'; _Component2['default'].registerComponent('MuteToggle', MuteToggle); exports['default'] = MuteToggle; module.exports = exports['default']; },{"../button":51,"../component":52,"../utils/dom.js":110}],57:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file play-toggle.js */ var _Button2 = _dereq_('../button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * Button to toggle between play and pause * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PlayToggle */ var PlayToggle = (function (_Button) { function PlayToggle(player, options) { _classCallCheck(this, PlayToggle); _Button.call(this, player, options); this.on(player, 'play', this.handlePlay); this.on(player, 'pause', this.handlePause); } _inherits(PlayToggle, _Button); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlayToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click to toggle between play and pause * * @method handleClick */ PlayToggle.prototype.handleClick = function handleClick() { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Add the vjs-playing class to the element so it can change appearance * * @method handlePlay */ PlayToggle.prototype.handlePlay = function handlePlay() { this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.controlText('Pause'); // change the button text to "Pause" }; /** * Add the vjs-paused class to the element so it can change appearance * * @method handlePause */ PlayToggle.prototype.handlePause = function handlePause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.controlText('Play'); // change the button text to "Play" }; return PlayToggle; })(_Button3['default']); PlayToggle.prototype.controlText_ = 'Play'; _Component2['default'].registerComponent('PlayToggle', PlayToggle); exports['default'] = PlayToggle; module.exports = exports['default']; },{"../button.js":51,"../component.js":52}],58:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file playback-rate-menu-button.js */ var _MenuButton2 = _dereq_('../../menu/menu-button.js'); var _MenuButton3 = _interopRequireWildcard(_MenuButton2); var _Menu = _dereq_('../../menu/menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _PlaybackRateMenuItem = _dereq_('./playback-rate-menu-item.js'); var _PlaybackRateMenuItem2 = _interopRequireWildcard(_PlaybackRateMenuItem); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * The component for controlling the playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class PlaybackRateMenuButton */ var PlaybackRateMenuButton = (function (_MenuButton) { function PlaybackRateMenuButton(player, options) { _classCallCheck(this, PlaybackRateMenuButton); _MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } _inherits(PlaybackRateMenuButton, _MenuButton); /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlaybackRateMenuButton.prototype.createEl = function createEl() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = Dom.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1 }); el.appendChild(this.labelEl_); return el; }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this); }; /** * Create the playback rate menu * * @return {Menu} Menu object populated with items * @method createMenu */ PlaybackRateMenuButton.prototype.createMenu = function createMenu() { var menu = new _Menu2['default'](this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new _PlaybackRateMenuItem2['default'](this.player(), { rate: rates[i] + 'x' })); } } return menu; }; /** * Updates ARIA accessibility attributes * * @method updateARIAAttributes */ PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; /** * Handle menu item click * * @method handleClick */ PlaybackRateMenuButton.prototype.handleClick = function handleClick() { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; /** * Get possible playback rates * * @return {Array} Possible playback rates * @method playbackRates */ PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() { return this.options_.playbackRates || this.options_.playerOptions && this.options_.playerOptions.playbackRates; }; /** * Get supported playback rates * * @return {Array} Supported playback rates * @method playbackRateSupported */ PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() { return this.player().tech && this.player().tech.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0; }; /** * Hide playback rate controls when they're no playback rate options to select * * @method updateVisibility */ PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed * * @method updateLabel */ PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; })(_MenuButton3['default']); PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; _Component2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); exports['default'] = PlaybackRateMenuButton; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-button.js":89,"../../menu/menu.js":91,"../../utils/dom.js":110,"./playback-rate-menu-item.js":59}],59:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file playback-rate-menu-item.js */ var _MenuItem2 = _dereq_('../../menu/menu-item.js'); var _MenuItem3 = _interopRequireWildcard(_MenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * The specific menu item type for selecting a playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class PlaybackRateMenuItem */ var PlaybackRateMenuItem = (function (_MenuItem) { function PlaybackRateMenuItem(player, options) { _classCallCheck(this, PlaybackRateMenuItem); var label = options.rate; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options.label = label; options.selected = rate === 1; _MenuItem.call(this, player, options); this.label = label; this.rate = rate; this.on(player, 'ratechange', this.update); } _inherits(PlaybackRateMenuItem, _MenuItem); /** * Handle click on menu item * * @method handleClick */ PlaybackRateMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); }; /** * Update playback rate with selected rate * * @method update */ PlaybackRateMenuItem.prototype.update = function update() { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; })(_MenuItem3['default']); PlaybackRateMenuItem.prototype.contentElType = 'button'; _Component2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); exports['default'] = PlaybackRateMenuItem; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-item.js":90}],60:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file load-progress-bar.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * Shows load progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class LoadProgressBar */ var LoadProgressBar = (function (_Component) { function LoadProgressBar(player, options) { _classCallCheck(this, LoadProgressBar); _Component.call(this, player, options); this.on(player, 'progress', this.update); } _inherits(LoadProgressBar, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ LoadProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; /** * Update progress bar * * @method update */ LoadProgressBar.prototype.update = function update() { var buffered = this.player_.buffered(); var duration = this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.el_.children; // get the percent width of a time compared to the total end var percentify = function percentify(time, end) { var percent = time / end || 0; // no NaN return (percent >= 1 ? 1 : percent) * 100 + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(Dom.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i - 1]); } }; return LoadProgressBar; })(_Component3['default']); _Component3['default'].registerComponent('LoadProgressBar', LoadProgressBar); exports['default'] = LoadProgressBar; module.exports = exports['default']; },{"../../component.js":52,"../../utils/dom.js":110}],61:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file play-progress-bar.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Shows play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class PlayProgressBar */ var PlayProgressBar = (function (_Component) { function PlayProgressBar(player, options) { _classCallCheck(this, PlayProgressBar); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateDataAttr); player.ready(Fn.bind(this, this.updateDataAttr)); } _inherits(PlayProgressBar, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlayProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() { var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('data-current-time', _formatTime2['default'](time, this.player_.duration())); }; return PlayProgressBar; })(_Component3['default']); _Component3['default'].registerComponent('PlayProgressBar', PlayProgressBar); exports['default'] = PlayProgressBar; module.exports = exports['default']; },{"../../component.js":52,"../../utils/fn.js":112,"../../utils/format-time.js":113}],62:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file progress-control.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _SeekBar = _dereq_('./seek-bar.js'); var _SeekBar2 = _interopRequireWildcard(_SeekBar); /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class ProgressControl */ var ProgressControl = (function (_Component) { function ProgressControl() { _classCallCheck(this, ProgressControl); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(ProgressControl, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ ProgressControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; return ProgressControl; })(_Component3['default']); ProgressControl.prototype.options_ = { children: { seekBar: {} } }; _Component3['default'].registerComponent('ProgressControl', ProgressControl); exports['default'] = ProgressControl; module.exports = exports['default']; },{"../../component.js":52,"./seek-bar.js":63}],63:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file seek-bar.js */ var _Slider2 = _dereq_('../../slider/slider.js'); var _Slider3 = _interopRequireWildcard(_Slider2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _LoadProgressBar = _dereq_('./load-progress-bar.js'); var _LoadProgressBar2 = _interopRequireWildcard(_LoadProgressBar); var _PlayProgressBar = _dereq_('./play-progress-bar.js'); var _PlayProgressBar2 = _interopRequireWildcard(_PlayProgressBar); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); var _roundFloat = _dereq_('../../utils/round-float.js'); var _roundFloat2 = _interopRequireWildcard(_roundFloat); /** * Seek Bar and holder for the progress bars * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class SeekBar */ var SeekBar = (function (_Slider) { function SeekBar(player, options) { _classCallCheck(this, SeekBar); _Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } _inherits(SeekBar, _Slider); /** * Create the component's DOM element * * @return {Element} * @method createEl */ SeekBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ SeekBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow', _roundFloat2['default'](this.getPercent() * 100, 2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext', _formatTime2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete) }; /** * Get percentage of video played * * @return {Number} Percentage played * @method getPercent */ SeekBar.prototype.getPercent = function getPercent() { var percent = this.player_.currentTime() / this.player_.duration(); return percent >= 1 ? 1 : percent; }; /** * Handle mouse down on seek bar * * @method handleMouseDown */ SeekBar.prototype.handleMouseDown = function handleMouseDown(event) { _Slider.prototype.handleMouseDown.call(this, event); this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; /** * Handle mouse move on seek bar * * @method handleMouseMove */ SeekBar.prototype.handleMouseMove = function handleMouseMove(event) { var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; /** * Handle mouse up on seek bar * * @method handleMouseUp */ SeekBar.prototype.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } }; /** * Move more quickly fast forward for keyboard-only users * * @method stepForward */ SeekBar.prototype.stepForward = function stepForward() { this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; /** * Move more quickly rewind for keyboard-only users * * @method stepBack */ SeekBar.prototype.stepBack = function stepBack() { this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; return SeekBar; })(_Slider3['default']); SeekBar.prototype.options_ = { children: { loadProgressBar: {}, playProgressBar: {} }, barName: 'playProgressBar' }; SeekBar.prototype.playerEvent = 'timeupdate'; _Component2['default'].registerComponent('SeekBar', SeekBar); exports['default'] = SeekBar; module.exports = exports['default']; },{"../../component.js":52,"../../slider/slider.js":96,"../../utils/fn.js":112,"../../utils/format-time.js":113,"../../utils/round-float.js":117,"./load-progress-bar.js":60,"./play-progress-bar.js":61}],64:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file custom-control-spacer.js */ var _Spacer2 = _dereq_('./spacer.js'); var _Spacer3 = _interopRequireWildcard(_Spacer2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer * @class CustomControlSpacer */ var CustomControlSpacer = (function (_Spacer) { function CustomControlSpacer() { _classCallCheck(this, CustomControlSpacer); if (_Spacer != null) { _Spacer.apply(this, arguments); } } _inherits(CustomControlSpacer, _Spacer); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ CustomControlSpacer.prototype.createEl = function createEl() { return _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); }; return CustomControlSpacer; })(_Spacer3['default']); _Component2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer); exports['default'] = CustomControlSpacer; module.exports = exports['default']; },{"../../component.js":52,"./spacer.js":65}],65:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file spacer.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component * @class Spacer */ var Spacer = (function (_Component) { function Spacer() { _classCallCheck(this, Spacer); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(Spacer, _Component); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Spacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @param {Object} props An object of properties * @return {Element} * @method createEl */ Spacer.prototype.createEl = function createEl(props) { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; })(_Component3['default']); _Component3['default'].registerComponent('Spacer', Spacer); exports['default'] = Spacer; module.exports = exports['default']; },{"../../component.js":52}],66:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file caption-settings-menu-item.js */ var _TextTrackMenuItem2 = _dereq_('./text-track-menu-item.js'); var _TextTrackMenuItem3 = _interopRequireWildcard(_TextTrackMenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * The menu item for caption track settings menu * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class CaptionSettingsMenuItem */ var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) { function CaptionSettingsMenuItem(player, options) { _classCallCheck(this, CaptionSettingsMenuItem); options.track = { kind: options.kind, player: player, label: options.kind + ' settings', 'default': false, mode: 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.addClass('vjs-texttrack-settings'); } _inherits(CaptionSettingsMenuItem, _TextTrackMenuItem); /** * Handle click on menu item * * @method handleClick */ CaptionSettingsMenuItem.prototype.handleClick = function handleClick() { this.player().getChild('textTrackSettings').show(); }; return CaptionSettingsMenuItem; })(_TextTrackMenuItem3['default']); _Component2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); exports['default'] = CaptionSettingsMenuItem; module.exports = exports['default']; },{"../../component.js":52,"./text-track-menu-item.js":73}],67:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file captions-button.js */ var _TextTrackButton2 = _dereq_('./text-track-button.js'); var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _CaptionSettingsMenuItem = _dereq_('./caption-settings-menu-item.js'); var _CaptionSettingsMenuItem2 = _interopRequireWildcard(_CaptionSettingsMenuItem); /** * The button component for toggling and selecting captions * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class CaptionsButton */ var CaptionsButton = (function (_TextTrackButton) { function CaptionsButton(player, options, ready) { _classCallCheck(this, CaptionsButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Captions Menu'); } _inherits(CaptionsButton, _TextTrackButton); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CaptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update caption menu items * * @method update */ CaptionsButton.prototype.update = function update() { var threshold = 2; _TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech && this.player().tech.featuresNativeTextTracks) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * Create caption menu items * * @return {Array} Array of menu items * @method createItems */ CaptionsButton.prototype.createItems = function createItems() { var items = []; if (!(this.player().tech && this.player().tech.featuresNativeTextTracks)) { items.push(new _CaptionSettingsMenuItem2['default'](this.player_, { kind: this.kind_ })); } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; })(_TextTrackButton3['default']); CaptionsButton.prototype.kind_ = 'captions'; CaptionsButton.prototype.controlText_ = 'Captions'; _Component2['default'].registerComponent('CaptionsButton', CaptionsButton); exports['default'] = CaptionsButton; module.exports = exports['default']; },{"../../component.js":52,"./caption-settings-menu-item.js":66,"./text-track-button.js":72}],68:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file chapters-button.js */ var _TextTrackButton2 = _dereq_('./text-track-button.js'); var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _TextTrackMenuItem = _dereq_('./text-track-menu-item.js'); var _TextTrackMenuItem2 = _interopRequireWildcard(_TextTrackMenuItem); var _ChaptersTrackMenuItem = _dereq_('./chapters-track-menu-item.js'); var _ChaptersTrackMenuItem2 = _interopRequireWildcard(_ChaptersTrackMenuItem); var _Menu = _dereq_('../../menu/menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _toTitleCase = _dereq_('../../utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class ChaptersButton */ var ChaptersButton = (function (_TextTrackButton) { function ChaptersButton(player, options, ready) { _classCallCheck(this, ChaptersButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Chapters Menu'); } _inherits(ChaptersButton, _TextTrackButton); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ ChaptersButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Create a menu item for each text track * * @return {Array} Array of menu items * @method createItems */ ChaptersButton.prototype.createItems = function createItems() { var items = []; var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track.kind === this.kind_) { items.push(new _TextTrackMenuItem2['default'](this.player_, { track: track })); } } return items; }; /** * Create menu from chapter buttons * * @return {Menu} Menu of chapter buttons * @method createMenu */ ChaptersButton.prototype.createMenu = function createMenu() { var tracks = this.player_.textTracks() || []; var chaptersTrack = undefined; var items = this.items = []; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind === this.kind_) { if (!track.cues) { track.mode = 'hidden'; /* jshint loopfunc:true */ // TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864 _window2['default'].setTimeout(Fn.bind(this, function () { this.createMenu(); }), 100); /* jshint loopfunc:false */ } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new _Menu2['default'](this.player_); menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _toTitleCase2['default'](this.kind_), tabIndex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack.cues, cue = undefined; for (var i = 0, l = cues.length; i < l; i++) { cue = cues[i]; var mi = new _ChaptersTrackMenuItem2['default'](this.player_, { track: chaptersTrack, cue: cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; return ChaptersButton; })(_TextTrackButton3['default']); ChaptersButton.prototype.kind_ = 'chapters'; ChaptersButton.prototype.controlText_ = 'Chapters'; _Component2['default'].registerComponent('ChaptersButton', ChaptersButton); exports['default'] = ChaptersButton; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu.js":91,"../../utils/dom.js":110,"../../utils/fn.js":112,"../../utils/to-title-case.js":119,"./chapters-track-menu-item.js":69,"./text-track-button.js":72,"./text-track-menu-item.js":73,"global/window":2}],69:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file chapters-track-menu-item.js */ var _MenuItem2 = _dereq_('../../menu/menu-item.js'); var _MenuItem3 = _interopRequireWildcard(_MenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); /** * The chapter track menu item * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class ChaptersTrackMenuItem */ var ChaptersTrackMenuItem = (function (_MenuItem) { function ChaptersTrackMenuItem(player, options) { _classCallCheck(this, ChaptersTrackMenuItem); var track = options.track; var cue = options.cue; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options.label = cue.text; options.selected = cue.startTime <= currentTime && currentTime < cue.endTime; _MenuItem.call(this, player, options); this.track = track; this.cue = cue; track.addEventListener('cuechange', Fn.bind(this, this.update)); } _inherits(ChaptersTrackMenuItem, _MenuItem); /** * Handle click on menu item * * @method handleClick */ ChaptersTrackMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; /** * Update chapter menu item * * @method update */ ChaptersTrackMenuItem.prototype.update = function update() { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue.startTime <= currentTime && currentTime < cue.endTime); }; return ChaptersTrackMenuItem; })(_MenuItem3['default']); _Component2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); exports['default'] = ChaptersTrackMenuItem; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-item.js":90,"../../utils/fn.js":112}],70:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file off-text-track-menu-item.js */ var _TextTrackMenuItem2 = _dereq_('./text-track-menu-item.js'); var _TextTrackMenuItem3 = _interopRequireWildcard(_TextTrackMenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * A special menu item for turning of a specific type of text track * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class OffTextTrackMenuItem */ var OffTextTrackMenuItem = (function (_TextTrackMenuItem) { function OffTextTrackMenuItem(player, options) { _classCallCheck(this, OffTextTrackMenuItem); // Create pseudo track info // Requires options['kind'] options.track = { kind: options.kind, player: player, label: options.kind + ' off', 'default': false, mode: 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.selected(true); } _inherits(OffTextTrackMenuItem, _TextTrackMenuItem); /** * Handle text track change * * @param {Object} event Event object * @method handleTracksChange */ OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var selected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track.kind === this.track.kind && track.mode === 'showing') { selected = false; break; } } this.selected(selected); }; return OffTextTrackMenuItem; })(_TextTrackMenuItem3['default']); _Component2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); exports['default'] = OffTextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":52,"./text-track-menu-item.js":73}],71:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file subtitles-button.js */ var _TextTrackButton2 = _dereq_('./text-track-button.js'); var _TextTrackButton3 = _interopRequireWildcard(_TextTrackButton2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); /** * The button component for toggling and selecting subtitles * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class SubtitlesButton */ var SubtitlesButton = (function (_TextTrackButton) { function SubtitlesButton(player, options, ready) { _classCallCheck(this, SubtitlesButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Subtitles Menu'); } _inherits(SubtitlesButton, _TextTrackButton); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return SubtitlesButton; })(_TextTrackButton3['default']); SubtitlesButton.prototype.kind_ = 'subtitles'; SubtitlesButton.prototype.controlText_ = 'Subtitles'; _Component2['default'].registerComponent('SubtitlesButton', SubtitlesButton); exports['default'] = SubtitlesButton; module.exports = exports['default']; },{"../../component.js":52,"./text-track-button.js":72}],72:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file text-track-button.js */ var _MenuButton2 = _dereq_('../../menu/menu-button.js'); var _MenuButton3 = _interopRequireWildcard(_MenuButton2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _TextTrackMenuItem = _dereq_('./text-track-menu-item.js'); var _TextTrackMenuItem2 = _interopRequireWildcard(_TextTrackMenuItem); var _OffTextTrackMenuItem = _dereq_('./off-text-track-menu-item.js'); var _OffTextTrackMenuItem2 = _interopRequireWildcard(_OffTextTrackMenuItem); /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class TextTrackButton */ var TextTrackButton = (function (_MenuButton) { function TextTrackButton(player, options) { _classCallCheck(this, TextTrackButton); _MenuButton.call(this, player, options); var tracks = this.player_.textTracks(); if (this.items.length <= 1) { this.hide(); } if (!tracks) { return; } var updateHandler = Fn.bind(this, this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); } _inherits(TextTrackButton, _MenuButton); // Create a menu item for each text track TextTrackButton.prototype.createItems = function createItems() { var items = arguments[0] === undefined ? [] : arguments[0]; // Add an OFF menu item to turn all tracks off items.push(new _OffTextTrackMenuItem2['default'](this.player_, { kind: this.kind_ })); var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track.kind === this.kind_) { items.push(new _TextTrackMenuItem2['default'](this.player_, { track: track })); } } return items; }; return TextTrackButton; })(_MenuButton3['default']); _Component2['default'].registerComponent('TextTrackButton', TextTrackButton); exports['default'] = TextTrackButton; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-button.js":89,"../../utils/fn.js":112,"./off-text-track-menu-item.js":70,"./text-track-menu-item.js":73}],73:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file text-track-menu-item.js */ var _MenuItem2 = _dereq_('../../menu/menu-item.js'); var _MenuItem3 = _interopRequireWildcard(_MenuItem2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /** * The specific menu item type for selecting a language within a text track kind * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class TextTrackMenuItem */ var TextTrackMenuItem = (function (_MenuItem) { function TextTrackMenuItem(player, options) { var _this = this; _classCallCheck(this, TextTrackMenuItem); var track = options.track; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options.label = track.label || track.language || 'Unknown'; options.selected = track['default'] || track.mode === 'showing'; _MenuItem.call(this, player, options); this.track = track; if (tracks) { (function () { var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); })(); } // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { (function () { var event = undefined; _this.on(['tap', 'click'], function () { if (typeof _window2['default'].Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new _window2['default'].Event('change'); } catch (err) {} } if (!event) { event = _document2['default'].createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); })(); } } _inherits(TextTrackMenuItem, _MenuItem); /** * Handle click on text track * * @method handleClick */ TextTrackMenuItem.prototype.handleClick = function handleClick(event) { var kind = this.track.kind; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) { return; }for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track.kind !== kind) { continue; } if (track === this.track) { track.mode = 'showing'; } else { track.mode = 'disabled'; } } }; /** * Handle text track change * * @method handleTracksChange */ TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track.mode === 'showing'); }; return TextTrackMenuItem; })(_MenuItem3['default']); _Component2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem); exports['default'] = TextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":52,"../../menu/menu-item.js":90,"../../utils/fn.js":112,"global/document":1,"global/window":2}],74:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file current-time-display.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Displays the current time * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class CurrentTimeDisplay */ var CurrentTimeDisplay = (function (_Component) { function CurrentTimeDisplay(player, options) { _classCallCheck(this, CurrentTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } _inherits(CurrentTimeDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ CurrentTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-current-time-display', innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update current time display * * @method updateContent */ CurrentTimeDisplay.prototype.updateContent = function updateContent() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing ? this.player_.getCache().currentTime : this.player_.currentTime(); var localizedText = this.localize('Current Time'); var formattedTime = _formatTime2['default'](time, this.player_.duration()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; }; return CurrentTimeDisplay; })(_Component3['default']); _Component3['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); exports['default'] = CurrentTimeDisplay; module.exports = exports['default']; },{"../../component.js":52,"../../utils/dom.js":110,"../../utils/format-time.js":113}],75:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file duration-display.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Displays the duration * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class DurationDisplay */ var DurationDisplay = (function (_Component) { function DurationDisplay(player, options) { _classCallCheck(this, DurationDisplay); _Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); this.on(player, 'loadedmetadata', this.updateContent); } _inherits(DurationDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ DurationDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update duration time display * * @method updateContent */ DurationDisplay.prototype.updateContent = function updateContent() { var duration = this.player_.duration(); if (duration) { var localizedText = this.localize('Duration Time'); var formattedTime = _formatTime2['default'](duration); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users } }; return DurationDisplay; })(_Component3['default']); _Component3['default'].registerComponent('DurationDisplay', DurationDisplay); exports['default'] = DurationDisplay; module.exports = exports['default']; },{"../../component.js":52,"../../utils/dom.js":110,"../../utils/format-time.js":113}],76:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file remaining-time-display.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _formatTime = _dereq_('../../utils/format-time.js'); var _formatTime2 = _interopRequireWildcard(_formatTime); /** * Displays the time left in the video * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class RemainingTimeDisplay */ var RemainingTimeDisplay = (function (_Component) { function RemainingTimeDisplay(player, options) { _classCallCheck(this, RemainingTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } _inherits(RemainingTimeDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ RemainingTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-remaining-time-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update remaining time display * * @method updateContent */ RemainingTimeDisplay.prototype.updateContent = function updateContent() { if (this.player_.duration()) { var localizedText = this.localize('Remaining Time'); var formattedTime = _formatTime2['default'](this.player_.remainingTime()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime; } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; return RemainingTimeDisplay; })(_Component3['default']); _Component3['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); exports['default'] = RemainingTimeDisplay; module.exports = exports['default']; },{"../../component.js":52,"../../utils/dom.js":110,"../../utils/format-time.js":113}],77:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file time-divider.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class TimeDivider */ var TimeDivider = (function (_Component) { function TimeDivider() { _classCallCheck(this, TimeDivider); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(TimeDivider, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ TimeDivider.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; return TimeDivider; })(_Component3['default']); _Component3['default'].registerComponent('TimeDivider', TimeDivider); exports['default'] = TimeDivider; module.exports = exports['default']; },{"../../component.js":52}],78:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file volume-bar.js */ var _Slider2 = _dereq_('../../slider/slider.js'); var _Slider3 = _interopRequireWildcard(_Slider2); var _Component = _dereq_('../../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _roundFloat = _dereq_('../../utils/round-float.js'); var _roundFloat2 = _interopRequireWildcard(_roundFloat); // Required children var _VolumeLevel = _dereq_('./volume-level.js'); var _VolumeLevel2 = _interopRequireWildcard(_VolumeLevel); /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class VolumeBar */ var VolumeBar = (function (_Slider) { function VolumeBar(player, options) { _classCallCheck(this, VolumeBar); _Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } _inherits(VolumeBar, _Slider); /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; /** * Handle mouse move on volume bar * * @method handleMouseMove */ VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; /** * Get percent of volume level * * @retun {Number} Volume level percent * @method getPercent */ VolumeBar.prototype.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; /** * Increase volume level for keyboard users * * @method stepForward */ VolumeBar.prototype.stepForward = function stepForward() { this.player_.volume(this.player_.volume() + 0.1); }; /** * Decrease volume level for keyboard users * * @method stepBack */ VolumeBar.prototype.stepBack = function stepBack() { this.player_.volume(this.player_.volume() - 0.1); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current value of volume bar as a percentage this.el_.setAttribute('aria-valuenow', _roundFloat2['default'](this.player_.volume() * 100, 2)); this.el_.setAttribute('aria-valuetext', _roundFloat2['default'](this.player_.volume() * 100, 2) + '%'); }; return VolumeBar; })(_Slider3['default']); VolumeBar.prototype.options_ = { children: { volumeLevel: {} }, barName: 'volumeLevel' }; VolumeBar.prototype.playerEvent = 'volumechange'; _Component2['default'].registerComponent('VolumeBar', VolumeBar); exports['default'] = VolumeBar; module.exports = exports['default']; },{"../../component.js":52,"../../slider/slider.js":96,"../../utils/fn.js":112,"../../utils/round-float.js":117,"./volume-level.js":80}],79:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file volume-control.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); // Required children var _VolumeBar = _dereq_('./volume-bar.js'); var _VolumeBar2 = _interopRequireWildcard(_VolumeBar); /** * The component for controlling the volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeControl */ var VolumeControl = (function (_Component) { function VolumeControl(player, options) { _classCallCheck(this, VolumeControl); _Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } _inherits(VolumeControl, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; return VolumeControl; })(_Component3['default']); VolumeControl.prototype.options_ = { children: { volumeBar: {} } }; _Component3['default'].registerComponent('VolumeControl', VolumeControl); exports['default'] = VolumeControl; module.exports = exports['default']; },{"../../component.js":52,"./volume-bar.js":78}],80:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file volume-level.js */ var _Component2 = _dereq_('../../component.js'); var _Component3 = _interopRequireWildcard(_Component2); /** * Shows volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeLevel */ var VolumeLevel = (function (_Component) { function VolumeLevel() { _classCallCheck(this, VolumeLevel); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(VolumeLevel, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeLevel.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; })(_Component3['default']); _Component3['default'].registerComponent('VolumeLevel', VolumeLevel); exports['default'] = VolumeLevel; module.exports = exports['default']; },{"../../component.js":52}],81:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file volume-menu-button.js */ var _Button = _dereq_('../button.js'); var _Button2 = _interopRequireWildcard(_Button); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _Menu = _dereq_('../menu/menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _MenuButton2 = _dereq_('../menu/menu-button.js'); var _MenuButton3 = _interopRequireWildcard(_MenuButton2); var _MuteToggle = _dereq_('./mute-toggle.js'); var _MuteToggle2 = _interopRequireWildcard(_MuteToggle); var _VolumeBar = _dereq_('./volume-control/volume-bar.js'); var _VolumeBar2 = _interopRequireWildcard(_VolumeBar); /** * Button for volume menu * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class VolumeMenuButton */ var VolumeMenuButton = (function (_MenuButton) { function VolumeMenuButton(player) { var options = arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, VolumeMenuButton); // If the vertical option isn't passed at all, default to true. if (options.vertical === undefined) { // If an inline volumeMenuButton is used, we should default to using a horizontal // slider for obvious reasons. if (options.inline) { options.vertical = false; } else { options.vertical = true; } } // The vertical option needs to be set on the volumeBar as well, since that will // need to be passed along to the VolumeBar constructor options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = !!options.vertical; _MenuButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech.featuresVolumeControl === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); this.addClass('vjs-menu-button'); } _inherits(VolumeMenuButton, _MenuButton); /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() { var orientationClass = ''; if (!!this.options_.vertical) { orientationClass = 'vjs-volume-menu-button-vertical'; } else { orientationClass = 'vjs-volume-menu-button-horizontal'; } return 'vjs-volume-menu-button ' + _MenuButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass; }; /** * Allow sub components to stack CSS class names * * @return {Menu} The volume menu button * @method createMenu */ VolumeMenuButton.prototype.createMenu = function createMenu() { var menu = new _Menu2['default'](this.player_, { contentElType: 'div' }); var vc = new _VolumeBar2['default'](this.player_, this.options_.volumeBar); vc.on('focus', function () { menu.lockShowing(); }); vc.on('blur', function () { menu.unlockShowing(); }); menu.addChild(vc); return menu; }; /** * Handle click on volume menu and calls super * * @method handleClick */ VolumeMenuButton.prototype.handleClick = function handleClick() { _MuteToggle2['default'].prototype.handleClick.call(this); _MenuButton.prototype.handleClick.call(this); }; return VolumeMenuButton; })(_MenuButton3['default']); VolumeMenuButton.prototype.volumeUpdate = _MuteToggle2['default'].prototype.update; VolumeMenuButton.prototype.controlText_ = 'Mute'; _Component2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton); exports['default'] = VolumeMenuButton; module.exports = exports['default']; },{"../button.js":51,"../component.js":52,"../menu/menu-button.js":89,"../menu/menu.js":91,"./mute-toggle.js":56,"./volume-control/volume-bar.js":78}],82:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file error-display.js */ var _Component2 = _dereq_('./component'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import); /** * Display that an error has occurred making the video unplayable * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class ErrorDisplay */ var ErrorDisplay = (function (_Component) { function ErrorDisplay(player, options) { _classCallCheck(this, ErrorDisplay); _Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } _inherits(ErrorDisplay, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ ErrorDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = Dom.createEl('div'); el.appendChild(this.contentEl_); return el; }; /** * Update the error message in localized language * * @method update */ ErrorDisplay.prototype.update = function update() { if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; return ErrorDisplay; })(_Component3['default']); _Component3['default'].registerComponent('ErrorDisplay', ErrorDisplay); exports['default'] = ErrorDisplay; module.exports = exports['default']; },{"./component":52,"./utils/dom.js":110}],83:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file event-emitter.js */ var _import = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import); var EventEmitter = function EventEmitter() {}; EventEmitter.prototype.allowedEvents_ = {}; EventEmitter.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = Function.prototype; Events.on(this, type, fn); this.addEventListener = ael; }; EventEmitter.prototype.addEventListener = EventEmitter.prototype.on; EventEmitter.prototype.off = function (type, fn) { Events.off(this, type, fn); }; EventEmitter.prototype.removeEventListener = EventEmitter.prototype.off; EventEmitter.prototype.one = function (type, fn) { Events.one(this, type, fn); }; EventEmitter.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; // The standard DOM EventTarget.dispatchEvent() is aliased to trigger() EventEmitter.prototype.dispatchEvent = EventEmitter.prototype.trigger; exports['default'] = EventEmitter; module.exports = exports['default']; },{"./utils/events.js":111}],84:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /* * @file extends.js * * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. */ var _inherits = function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) { // node subClass.super_ = superClass; } }; /* * Function for subclassing using the same inheritance that * videojs uses internally * ```js * var Button = videojs.getComponent('Button'); * ``` * ```js * var MyButton = videojs.extends(Button, { * constructor: function(player, options) { * Button.call(this, player, options); * }, * onClick: function() { * // doSomething * } * }); * ``` */ var extendsFn = function extendsFn(superClass) { var subClassMethods = arguments[1] === undefined ? {} : arguments[1]; var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if (typeof subClassMethods === 'object') { if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; exports['default'] = extendsFn; module.exports = exports['default']; },{}],85:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file fullscreen-api.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /* * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ var FullscreenApi = {}; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js var apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html ['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = undefined; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _document2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var i = 0; i < browserApi.length; i++) { FullscreenApi[specApi[i]] = browserApi[i]; } } exports['default'] = FullscreenApi; module.exports = exports['default']; },{"global/document":1}],86:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file global-options.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var navigator = _window2['default'].navigator; /* * Global Player instance options, surfaced from Player.prototype.options_ * options = Player.prototype.options_ * All options should use string keys so they avoid * renaming by closure compiler * * @type {Object} */ exports['default'] = { // Default order of fallback technology techOrder: ['html5', 'flash'], // techOrder: ['flash','html5'], html5: {}, flash: {}, // defaultVolume: 0.85, defaultVolume: 0, // The freakin seaguls are driving me crazy! // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: { mediaLoader: {}, posterImage: {}, textTrackDisplay: {}, loadingSpinner: {}, bigPlayButton: {}, controlBar: {}, errorDisplay: {}, textTrackSettings: {} }, language: _document2['default'].getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this video.' }; module.exports = exports['default']; },{"global/document":1,"global/window":2}],87:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file loading-spinner.js */ var _Component2 = _dereq_('./component'); var _Component3 = _interopRequireWildcard(_Component2); /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * * @extends Component * @class LoadingSpinner */ var LoadingSpinner = (function (_Component) { function LoadingSpinner() { _classCallCheck(this, LoadingSpinner); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(LoadingSpinner, _Component); /** * Create the component's DOM element * * @method createEl */ LoadingSpinner.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; return LoadingSpinner; })(_Component3['default']); _Component3['default'].registerComponent('LoadingSpinner', LoadingSpinner); exports['default'] = LoadingSpinner; module.exports = exports['default']; },{"./component":52}],88:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file media-error.js */ var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); /* * Custom MediaError to mimic the HTML5 MediaError * * @param {Number} code The media error code */ var MediaError = (function (_MediaError) { function MediaError(_x) { return _MediaError.apply(this, arguments); } MediaError.toString = function () { return _MediaError.toString(); }; return MediaError; })(function (code) { if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object _assign2['default'](this, code); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } }); /* * The error code that refers two one of the defined * MediaError types * * @type {Number} */ MediaError.prototype.code = 0; /* * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /* * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * * @type {Array} */ MediaError.prototype.status = null; MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; MediaError.defaultMessages = { 1: 'You aborted the video playback', 2: 'A network error caused the video download to fail part-way.', 3: 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.', 4: 'The video could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The video is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } exports['default'] = MediaError; module.exports = exports['default']; },{"object.assign":44}],89:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file menu-button.js */ var _Button2 = _dereq_('../button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _Menu = _dereq_('./menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _toTitleCase = _dereq_('../utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); /** * A button class with a popup menu * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuButton */ var MenuButton = (function (_Button) { function MenuButton(player) { var options = arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, MenuButton); _Button.call(this, player, options); this.update(); this.on('keydown', this.handleKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } _inherits(MenuButton, _Button); /** * Update menu * * @method update */ MenuButton.prototype.update = function update() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create menu * * @return {Menu} The constructed menu * @method createMenu */ MenuButton.prototype.createMenu = function createMenu() { var menu = new _Menu2['default'](this.player_); // Add a title list item to the top if (this.options_.title) { menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _toTitleCase2['default'](this.options_.title), tabIndex: -1 })); } this.items = this.createItems(); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. * * @method createItems */ MenuButton.prototype.createItems = function createItems() {}; /** * Create the component's DOM element * * @return {Element} * @method createEl */ MenuButton.prototype.createEl = function createEl() { return _Button.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MenuButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _Button.prototype.buildCSSClass.call(this); }; /** * Focus - Add keyboard functionality to element * This function is not needed anymore. Instead, the * keyboard functionality is handled by * treating the button as triggering a submenu. * When the button is pressed, the submenu * appears. Pressing the button again makes * the submenu disappear. * * @method handleFocus */ MenuButton.prototype.handleFocus = function handleFocus() {}; /** * Can't turn off list display that we turned * on with focus, because list would go away. * * @method handleBlur */ MenuButton.prototype.handleBlur = function handleBlur() {}; /** * When you click the button it adds focus, which * will show the menu indefinitely. * So we'll remove focus when the mouse leaves the button. * Focus is needed for tab navigation. * Allow sub components to stack CSS class names * * @method handleClick */ MenuButton.prototype.handleClick = function handleClick() { this.one('mouseout', Fn.bind(this, function () { this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } }; /** * Handle key press on menu * * @param {Object} Key press event * @method handleKeyPress */ MenuButton.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } event.preventDefault(); // Check for escape (27) key } else if (event.which === 27) { if (this.buttonPressed_) { this.unpressButton(); } event.preventDefault(); } }; /** * Makes changes based on button pressed * * @method pressButton */ MenuButton.prototype.pressButton = function pressButton() { this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; /** * Makes changes based on button unpressed * * @method unpressButton */ MenuButton.prototype.unpressButton = function unpressButton() { this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; return MenuButton; })(_Button3['default']); _Component2['default'].registerComponent('MenuButton', MenuButton); exports['default'] = MenuButton; module.exports = exports['default']; },{"../button.js":51,"../component.js":52,"../utils/dom.js":110,"../utils/fn.js":112,"../utils/to-title-case.js":119,"./menu.js":91}],90:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file menu-item.js */ var _Button2 = _dereq_('../button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('../component.js'); var _Component2 = _interopRequireWildcard(_Component); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); /** * The component for a menu item. `<li>` * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuItem */ var MenuItem = (function (_Button) { function MenuItem(player, options) { _classCallCheck(this, MenuItem); _Button.call(this, player, options); this.selected(options.selected); } _inherits(MenuItem, _Button); /** * Create the component's DOM element * * @param {String=} type Desc * @param {Object=} props Desc * @return {Element} * @method createEl */ MenuItem.prototype.createEl = function createEl(type, props) { return _Button.prototype.createEl.call(this, 'li', _assign2['default']({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_.label) }, props)); }; /** * Handle a click on the menu item, and set it to selected * * @method handleClick */ MenuItem.prototype.handleClick = function handleClick() { this.selected(true); }; /** * Set this menu item as selected or not * * @param {Boolean} selected * @method selected */ MenuItem.prototype.selected = (function (_selected) { function selected(_x) { return _selected.apply(this, arguments); } selected.toString = function () { return _selected.toString(); }; return selected; })(function (selected) { if (selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected', true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected', false); } }); return MenuItem; })(_Button3['default']); _Component2['default'].registerComponent('MenuItem', MenuItem); exports['default'] = MenuItem; module.exports = exports['default']; },{"../button.js":51,"../component.js":52,"object.assign":44}],91:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file menu.js */ var _Component2 = _dereq_('../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _import3 = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_import3); /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @extends Component * @class Menu */ var Menu = (function (_Component) { function Menu() { _classCallCheck(this, Menu); if (_Component != null) { _Component.apply(this, arguments); } } _inherits(Menu, _Component); /** * Add a menu item to the menu * * @param {Object|String} component Component or component type to add * @method addItem */ Menu.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function () { this.unlockShowing(); })); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Menu.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; return Menu; })(_Component3['default']); _Component3['default'].registerComponent('Menu', Menu); exports['default'] = Menu; module.exports = exports['default']; },{"../component.js":52,"../utils/dom.js":110,"../utils/events.js":111,"../utils/fn.js":112}],92:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file player.js */ // Subclasses Component var _Component2 = _dereq_('./component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _import = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import); var _import2 = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import2); var _import3 = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import3); var _import4 = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_import4); var _import5 = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_import5); var _log = _dereq_('./utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _toTitleCase = _dereq_('./utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); var _createTimeRange = _dereq_('./utils/time-ranges.js'); var _bufferedPercent2 = _dereq_('./utils/buffer.js'); var _FullscreenApi = _dereq_('./fullscreen-api.js'); var _FullscreenApi2 = _interopRequireWildcard(_FullscreenApi); var _MediaError = _dereq_('./media-error.js'); var _MediaError2 = _interopRequireWildcard(_MediaError); var _globalOptions = _dereq_('./global-options.js'); var _globalOptions2 = _interopRequireWildcard(_globalOptions); var _safeParseTuple2 = _dereq_('safe-json-parse/tuple'); var _safeParseTuple3 = _interopRequireWildcard(_safeParseTuple2); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var _mergeOptions = _dereq_('./utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); // Include required child components (importing also registers them) var _MediaLoader = _dereq_('./tech/loader.js'); var _MediaLoader2 = _interopRequireWildcard(_MediaLoader); var _PosterImage = _dereq_('./poster-image.js'); var _PosterImage2 = _interopRequireWildcard(_PosterImage); var _TextTrackDisplay = _dereq_('./tracks/text-track-display.js'); var _TextTrackDisplay2 = _interopRequireWildcard(_TextTrackDisplay); var _LoadingSpinner = _dereq_('./loading-spinner.js'); var _LoadingSpinner2 = _interopRequireWildcard(_LoadingSpinner); var _BigPlayButton = _dereq_('./big-play-button.js'); var _BigPlayButton2 = _interopRequireWildcard(_BigPlayButton); var _ControlBar = _dereq_('./control-bar/control-bar.js'); var _ControlBar2 = _interopRequireWildcard(_ControlBar); var _ErrorDisplay = _dereq_('./error-display.js'); var _ErrorDisplay2 = _interopRequireWildcard(_ErrorDisplay); var _TextTrackSettings = _dereq_('./tracks/text-track-settings.js'); var _TextTrackSettings2 = _interopRequireWildcard(_TextTrackSettings); // Require html5 tech, at least for disposing the original video tag var _Html5 = _dereq_('./tech/html5.js'); var _Html52 = _interopRequireWildcard(_Html5); /** * An instance of the `Player` class is created when any of the Video.js setup methods are used to initialize a video. * ```js * var myPlayer = videojs('example_video_1'); * ``` * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class Player */ var Player = (function (_Component) { /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ function Player(tag, options, ready) { var _this = this; _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + Guid.newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = _assign2['default'](Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options _Component.call(this, null, options, ready); // if the global option object was accidentally blown away by // someone, bail early with an informative error if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } this.tag = tag; // Store the original tag used to set options // Store the tag attributes used to restore html5 element this.tagAttributes = tag && Dom.getElAttributes(tag); // Update current language this.language(options.language || _globalOptions2['default'].language); // Update Supported Languages if (options.languages) { (function () { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; })(); } else { this.languages_ = _globalOptions2['default'].languages; } // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options.poster || ''; // Set controls this.controls_ = !!options.controls; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ this.scrubbing_ = false; this.el_ = this.createEl(); // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = _mergeOptions2['default']({}, this.options_); // Load plugins if (options.plugins) { (function () { var plugins = options.plugins; Object.getOwnPropertyNames(plugins).forEach(function (name) { plugins[name].playerOptions = playerOptionsCopy; if (typeof this[name] === 'function') { this[name](plugins[name]); } else { _log2['default'].error('Unable to find plugin:', name); } }, _this); })(); } this.options_.playerOptions = playerOptionsCopy; this.initChildren(); // Set isAudio based on whether or not an audio tag was used this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } if (this.flexNotSupported_()) { this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID Player.players[this.id_] = this; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed this.userActive_ = true; this.reportUserActivity(); this.listenForUserActivity(); this.on('fullscreenchange', this.handleFullscreenChange); this.on('stageclick', this.handleStageClick); } _inherits(Player, _Component); /** * Destroys the video player and does any necessary cleanup * ```js * myPlayer.dispose(); * ``` * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @method dispose */ Player.prototype.dispose = function dispose() { this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech) { this.tech.dispose(); } _Component.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Player.prototype.createEl = function createEl() { var el = this.el_ = _Component.prototype.createEl.call(this, 'div'); var tag = this.tag; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getElAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element this.styleEl_ = _document2['default'].createElement('style'); el.appendChild(this.styleEl_); // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. this.el_ = el; return el; }; /** * Get/set player width * * @param {Number=} value Value for width * @return {Number} Width when getting * @method width */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * Get/set player height * * @param {Number=} value Value for height * @return {Number} Height when getting * @method height */ Player.prototype.height = function height(value) { return this.dimension('height', value); }; /** * Get/set dimension for player * * @param {String} dimension Either width or height * @param {Number=} value Value for dimension * @return {Component} * @method dimension */ Player.prototype.dimension = (function (_dimension) { function dimension(_x, _x2) { return _dimension.apply(this, arguments); } dimension.toString = function () { return _dimension.toString(); }; return dimension; })(function (dimension, value) { var privDimension = dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _log2['default'].error('Improper value "' + value + '" supplied for for ' + dimension); return this; } this[privDimension] = parsedVal; } this.updateStyleEl_(); return this; }); /** * Add/remove the vjs-fluid class * * @param {Boolean} bool Value of true adds the class, value of false removes the class * @method fluid */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } }; /** * Get/Set the aspect ratio * * @param {String=} ratio Aspect ratio for player * @return aspectRatio * @method aspectRatio */ Player.prototype.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); }; /** * Update styles of the player element (height, width and aspect ratio) * * @method updateStyleEl_ */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { var width = undefined; var height = undefined; var aspectRatio = undefined; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth()) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } var idClass = this.id() + '-dimensions'; // Ensure the right class is still on the player for the style element this.addClass(idClass); // Create the width/height CSS var css = '.' + idClass + ' { width: ' + width + 'px; height: ' + height + 'px; }'; // Add the aspect ratio CSS for when using a fluid layout css += '.' + idClass + '.vjs-fluid { padding-top: ' + ratioMultiplier * 100 + '%; }'; // Update the style el if (this.styleEl_.styleSheet) { this.styleEl_.styleSheet.cssText = css; } else { this.styleEl_.innerHTML = css; } }; /** * Load the Media Playback Technology (tech) * Load/Create an instance of playback technology including element and API methods * And append playback element in player div. * * @param {String} techName Name of the playback technology * @param {String} source Video source * @method loadTech */ Player.prototype.loadTech = function loadTech(techName, source) { // Pause and remove current playback technology if (this.tech) { this.unloadTech(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { _Component3['default'].getComponent('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; var techReady = Fn.bind(this, function () { this.triggerReady(); }); // Grab tech-specific options from player options and add source and parent element to use. var techOptions = _assign2['default']({ source: source, playerId: this.id(), techId: '' + this.id() + '_' + techName + '_api', textTracks: this.textTracks_, autoplay: this.options_.autoplay, preload: this.options_.preload, loop: this.options_.loop, muted: this.options_.muted, poster: this.poster(), language: this.language() }, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source) { this.currentType_ = source.type; if (source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance var techComponent = _Component3['default'].getComponent(techName); this.tech = new techComponent(techOptions); this.on(this.tech, 'ready', this.handleTechReady); this.on(this.tech, 'usenativecontrols', this.handleTechUseNativeControls); // Listen to every HTML5 events and trigger them back on the player for the plugins this.on(this.tech, 'loadstart', this.handleTechLoadStart); this.on(this.tech, 'waiting', this.handleTechWaiting); this.on(this.tech, 'canplay', this.handleTechCanPlay); this.on(this.tech, 'canplaythrough', this.handleTechCanPlayThrough); this.on(this.tech, 'playing', this.handleTechPlaying); this.on(this.tech, 'ended', this.handleTechEnded); this.on(this.tech, 'seeking', this.handleTechSeeking); this.on(this.tech, 'seeked', this.handleTechSeeked); this.on(this.tech, 'play', this.handleTechPlay); this.on(this.tech, 'firstplay', this.handleTechFirstPlay); this.on(this.tech, 'pause', this.handleTechPause); this.on(this.tech, 'progress', this.handleTechProgress); this.on(this.tech, 'durationchange', this.handleTechDurationChange); this.on(this.tech, 'fullscreenchange', this.handleTechFullscreenChange); this.on(this.tech, 'error', this.handleTechError); this.on(this.tech, 'suspend', this.handleTechSuspend); this.on(this.tech, 'abort', this.handleTechAbort); this.on(this.tech, 'emptied', this.handleTechEmptied); this.on(this.tech, 'stalled', this.handleTechStalled); this.on(this.tech, 'loadedmetadata', this.handleTechLoadedMetaData); this.on(this.tech, 'loadeddata', this.handleTechLoadedData); this.on(this.tech, 'timeupdate', this.handleTechTimeUpdate); this.on(this.tech, 'ratechange', this.handleTechRateChange); this.on(this.tech, 'volumechange', this.handleTechVolumeChange); this.on(this.tech, 'texttrackchange', this.onTextTrackChange); this.on(this.tech, 'loadedmetadata', this.updateStyleEl_); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) { Dom.insertElFirst(this.tech.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } this.tech.ready(techReady); }; /** * Unload playback technology * * @method unloadTech */ Player.prototype.unloadTech = function unloadTech() { // Save the current text tracks so that we can reuse the same text tracks with the next tech this.textTracks_ = this.textTracks(); this.isReady_ = false; this.tech.dispose(); this.tech = false; }; /** * Add playback technology listeners * * @method addTechControlsListeners */ Player.prototype.addTechControlsListeners = function addTechControlsListeners() { // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech, 'mousedown', this.handleTechClick); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech, 'touchstart', this.handleTechTouchStart); this.on(this.tech, 'touchmove', this.handleTechTouchMove); this.on(this.tech, 'touchend', this.handleTechTouchEnd); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech, 'tap', this.handleTechTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @method removeTechControlsListeners */ Player.prototype.removeTechControlsListeners = function removeTechControlsListeners() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech, 'tap', this.handleTechTap); this.off(this.tech, 'touchstart', this.handleTechTouchStart); this.off(this.tech, 'touchmove', this.handleTechTouchMove); this.off(this.tech, 'touchend', this.handleTechTouchEnd); this.off(this.tech, 'mousedown', this.handleTechClick); }; /** * Player waits for the tech to be ready * * @private * @method handleTechReady */ Player.prototype.handleTechReady = function handleTechReady() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall('setVolume', this.cache_.volume); } // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if (this.tag && this.options_.autoplay && this.paused()) { delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16. this.play(); } }; /** * Fired when the native controls are used * * @private * @method handleTechUseNativeControls */ Player.prototype.handleTechUseNativeControls = function handleTechUseNativeControls() { this.usingNativeControls(true); }; /** * Fired when the user agent begins looking for media data * * @event loadstart */ Player.prototype.handleTechLoadStart = function handleTechLoadStart() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @param {Boolean} hasStarted The value of true adds the class the value of false remove the class * @return {Boolean} Boolean value if has started * @method hasStarted */ Player.prototype.hasStarted = (function (_hasStarted) { function hasStarted(_x3) { return _hasStarted.apply(this, arguments); } hasStarted.toString = function () { return _hasStarted.toString(); }; return hasStarted; })(function (hasStarted) { if (hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== hasStarted) { this.hasStarted_ = hasStarted; if (hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return !!this.hasStarted_; }); /** * Fired whenever the media begins or resumes playback * * @event play */ Player.prototype.handleTechPlay = function handleTechPlay() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play this.hasStarted(true); this.trigger('play'); }; /** * Fired whenever the media begins waiting * * @event waiting */ Player.prototype.handleTechWaiting = function handleTechWaiting() { this.addClass('vjs-waiting'); this.trigger('waiting'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event canplay */ Player.prototype.handleTechCanPlay = function handleTechCanPlay() { this.removeClass('vjs-waiting'); this.trigger('canplay'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event canplaythrough */ Player.prototype.handleTechCanPlayThrough = function handleTechCanPlayThrough() { this.removeClass('vjs-waiting'); this.trigger('canplaythrough'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event playing */ Player.prototype.handleTechPlaying = function handleTechPlaying() { this.removeClass('vjs-waiting'); this.trigger('playing'); }; /** * Fired whenever the player is jumping to a new time * * @event seeking */ Player.prototype.handleTechSeeking = function handleTechSeeking() { this.addClass('vjs-seeking'); this.trigger('seeking'); }; /** * Fired when the player has finished jumping to a new time * * @event seeked */ Player.prototype.handleTechSeeked = function handleTechSeeked() { this.removeClass('vjs-seeking'); this.trigger('seeked'); }; /** * Fired the first time a video is played * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @event firstplay */ Player.prototype.handleTechFirstPlay = function handleTechFirstPlay() { //If the first starttime attribute is specified //then we will start at the given offset in seconds if (this.options_.starttime) { this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); this.trigger('firstplay'); }; /** * Fired whenever the media has been paused * * @event pause */ Player.prototype.handleTechPause = function handleTechPause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.trigger('pause'); }; /** * Fired while the user agent is downloading media data * * @event progress */ Player.prototype.handleTechProgress = function handleTechProgress() { this.trigger('progress'); // Add custom event for when source is finished downloading. if (this.bufferedPercent() === 1) { this.trigger('loadedalldata'); } }; /** * Fired when the end of the media resource is reached (currentTime == duration) * * @event ended */ Player.prototype.handleTechEnded = function handleTechEnded() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @event durationchange */ Player.prototype.handleTechDurationChange = function handleTechDurationChange() { this.updateDuration(); this.trigger('durationchange'); }; /** * Handle a click on the media element to play/pause * * @param {Object=} event Event object * @method handleTechClick */ Player.prototype.handleTechClick = function handleTechClick(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) { return; } // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @method handleTechTap */ Player.prototype.handleTechTap = function handleTechTap() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @method handleTechTouchStart */ Player.prototype.handleTechTouchStart = function handleTechTouchStart() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @method handleTechTouchMove */ Player.prototype.handleTechTouchMove = function handleTechTouchMove() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @method handleTechTouchEnd */ Player.prototype.handleTechTouchEnd = function handleTechTouchEnd(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Update the duration of the player using the tech * * @private * @method updateDuration */ Player.prototype.updateDuration = function updateDuration() { // Allows for caching value instead of asking player each time. // We need to get the techGet response and check for a value so we don't // accidentally cause the stack to blow up. var duration = this.techGet('duration'); if (duration) { if (duration < 0) { duration = Infinity; } this.duration(duration); // Determine if the stream is live and propagate styles down to UI. if (duration === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } } }; /** * Fired when the player switches in or out of fullscreen mode * * @event fullscreenchange */ Player.prototype.handleFullscreenChange = function handleFullscreenChange() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @method handleStageClick */ Player.prototype.handleStageClick = function handleStageClick() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @method handleTechFullscreenChange */ Player.prototype.handleTechFullscreenChange = function handleTechFullscreenChange(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video * * @event error */ Player.prototype.handleTechError = function handleTechError() { this.error(this.tech.error().code); }; /** * Fires when the browser is intentionally not getting media data * * @event suspend */ Player.prototype.handleTechSuspend = function handleTechSuspend() { this.trigger('suspend'); }; /** * Fires when the loading of an audio/video is aborted * * @event abort */ Player.prototype.handleTechAbort = function handleTechAbort() { this.trigger('abort'); }; /** * Fires when the current playlist is empty * * @event emptied */ Player.prototype.handleTechEmptied = function handleTechEmptied() { this.trigger('emptied'); }; /** * Fires when the browser is trying to get media data, but data is not available * * @event stalled */ Player.prototype.handleTechStalled = function handleTechStalled() { this.trigger('stalled'); }; /** * Fires when the browser has loaded meta data for the audio/video * * @event loadedmetadata */ Player.prototype.handleTechLoadedMetaData = function handleTechLoadedMetaData() { this.trigger('loadedmetadata'); }; /** * Fires when the browser has loaded the current frame of the audio/video * * @event loaddata */ Player.prototype.handleTechLoadedData = function handleTechLoadedData() { this.trigger('loadeddata'); }; /** * Fires when the current playback position has changed * * @event timeupdate */ Player.prototype.handleTechTimeUpdate = function handleTechTimeUpdate() { this.trigger('timeupdate'); }; /** * Fires when the playing speed of the audio/video is changed * * @event ratechange */ Player.prototype.handleTechRateChange = function handleTechRateChange() { this.trigger('ratechange'); }; /** * Fires when the volume has been changed * * @event volumechange */ Player.prototype.handleTechVolumeChange = function handleTechVolumeChange() { this.trigger('volumechange'); }; /** * Fires when the text track has been changed * * @event texttrackchange */ Player.prototype.onTextTrackChange = function onTextTrackChange() { this.trigger('texttrackchange'); }; /** * Get object for cached values. * * @return {Object} * @method getCache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {String=} method Method * @param {Object=} arg Argument * @method techCall */ Player.prototype.techCall = function techCall(method, arg) { // If it's not ready yet, call method when it is if (this.tech && !this.tech.isReady_) { this.tech.ready(function () { this[method](arg); }); // Otherwise call method now } else { try { this.tech[method](arg); } catch (e) { _log2['default'](e); throw e; } } }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {String} method Tech method * @return {Method} * @method techGet */ Player.prototype.techGet = function techGet(method) { if (this.tech && this.tech.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech[method] === undefined) { _log2['default']('Video.js: ' + method + ' method not defined for ' + this.techName + ' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name === 'TypeError') { _log2['default']('Video.js: ' + method + ' unavailable on ' + this.techName + ' playback technology element.', e); this.tech.isReady_ = false; } else { _log2['default'](e); } } throw e; } } return; }; /** * start media playback * ```js * myPlayer.play(); * ``` * * @return {Player} self * @method play */ Player.prototype.play = function play() { this.techCall('play'); return this; }; /** * Pause the video playback * ```js * myPlayer.pause(); * ``` * * @return {Player} self * @method pause */ Player.prototype.pause = function pause() { this.techCall('pause'); return this; }; /** * Check if the player is paused * ```js * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * ``` * * @return {Boolean} false if the media is currently playing, or true otherwise * @method paused */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet('paused') === false ? false : true; }; /** * Returns whether or not the user is "scrubbing". Scrubbing is when the user * has clicked the progress bar handle and is dragging it along the progress bar. * * @param {Boolean} isScrubbing True/false the user is scrubbing * @return {Boolean} The scrubbing status when getting * @return {Object} The player when setting * @method scrubbing */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (isScrubbing !== undefined) { this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } return this; } return this.scrubbing_; }; /** * Get or set the current time (in seconds) * ```js * // get * var whereYouAt = myPlayer.currentTime(); * // set * myPlayer.currentTime(120); // 2 minutes into the video * ``` * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {Player} self, when the current time is set * @method currentTime */ Player.prototype.currentTime = function currentTime(seconds) { if (seconds !== undefined) { this.techCall('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = this.techGet('currentTime') || 0; }; /** * Get the length in time of the video in seconds * ```js * var lengthOfVideo = myPlayer.duration(); * ``` * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @param {Number} seconds Duration when setting * @return {Number} The duration of the video in seconds when getting * @method duration */ Player.prototype.duration = function duration(seconds) { if (seconds !== undefined) { // cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = parseFloat(seconds); return this; } if (this.cache_.duration === undefined) { this.updateDuration(); } return this.cache_.duration || 0; }; /** * Calculates how much time is left. * ```js * var timeLeft = myPlayer.remainingTime(); * ``` * Not a native video element function, but useful * * @return {Number} The time remaining in seconds * @method remainingTime */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * ```js * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * ``` * * @return {Object} A mock TimeRange object (following HTML spec) * @method buffered */ Player.prototype.buffered = (function (_buffered) { function buffered() { return _buffered.apply(this, arguments); } buffered.toString = function () { return _buffered.toString(); }; return buffered; })(function () { var buffered = this.techGet('buffered'); if (!buffered || !buffered.length) { buffered = _createTimeRange.createTimeRange(0, 0); } return buffered; }); /** * Get the percent (as a decimal) of the video that's been downloaded * ```js * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * ``` * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent * @method bufferedPercent */ Player.prototype.bufferedPercent = (function (_bufferedPercent) { function bufferedPercent() { return _bufferedPercent.apply(this, arguments); } bufferedPercent.toString = function () { return _bufferedPercent.toString(); }; return bufferedPercent; })(function () { return _bufferedPercent2.bufferedPercent(this.buffered(), this.duration()); }); /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {Number} The end of the last buffered time range * @method bufferedEnd */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * ```js * // get * var howLoudIsIt = myPlayer.volume(); * // set * myPlayer.volume(0.5); // Set volume to half * ``` * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume when getting * @return {Player} self when setting * @method volume */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = undefined; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall('setVolume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * ```js * // get * var isVolumeMuted = myPlayer.muted(); * // set * myPlayer.muted(true); // mute the volume * ``` * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not when getting * @return {Player} self when setting mute * @method muted */ Player.prototype.muted = (function (_muted) { function muted(_x4) { return _muted.apply(this, arguments); } muted.toString = function () { return _muted.toString(); }; return muted; })(function (muted) { if (muted !== undefined) { this.techCall('setMuted', muted); return this; } return this.techGet('muted') || false; // Default to false }); // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) /** * Check to see if fullscreen is supported * * @return {Boolean} * @method supportsFullScreen */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode * ```js * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * ``` * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen false if not when getting * @return {Player} self when setting * @method isFullscreen */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return !!this.isFullscreen_; }; /** * Old naming for isFullscreen() * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen false if not when getting * @return {Player} self when setting * @deprecated * @method isFullScreen */ Player.prototype.isFullScreen = function isFullScreen(isFS) { _log2['default'].warn('player.isFullScreen() has been deprecated, use player.isFullscreen() with a lowercase "s")'); return this.isFullscreen(isFS); }; /** * Increase the size of the video to full screen * ```js * myPlayer.requestFullscreen(); * ``` * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {Player} self * @method requestFullscreen */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _FullscreenApi2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_document2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_document2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_document2['default'], fsApi.fullscreenchange, documentFullscreenChange); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for requestFullscreen * * @return {Boolean} true if fullscreen false if not when getting * @deprecated * @method requestFullScreen */ Player.prototype.requestFullScreen = function requestFullScreen() { _log2['default'].warn('player.requestFullScreen() has been deprecated, use player.requestFullscreen() with a lowercase "s")'); return this.requestFullscreen(); }; /** * Return the video to its normal size after having been in full screen mode * ```js * myPlayer.exitFullscreen(); * ``` * * @return {Player} self * @method exitFullscreen */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _FullscreenApi2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _document2['default'][fsApi.exitFullscreen](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for exitFullscreen * * @return {Player} self * @deprecated * @method cancelFullScreen */ Player.prototype.cancelFullScreen = function cancelFullScreen() { _log2['default'].warn('player.cancelFullScreen() has been deprecated, use player.exitFullscreen()'); return this.exitFullscreen(); }; /** * When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. * * @method enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _document2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_document2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _document2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addElClass(_document2['default'].body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or full screen on ESC key * * @param {String} event Event to check for key press * @method fullWindowOnEscKey */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @method exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_document2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _document2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeElClass(_document2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; /** * Select source based on tech order * * @param {Array} sources The sources for a media asset * @return {Object|Boolean} Object of source and tech order, otherwise false * @method selectSource */ Player.prototype.selectSource = function selectSource(sources) { // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = _toTitleCase2['default'](j[i]); var tech = _Component3['default'].getComponent(techName); // Check if the current tech is defined before continuing if (!tech) { _log2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a = 0, b = sources; a < b.length; a++) { var source = b[a]; // Check if source can be played with this technology if (tech.canPlaySource(source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * ```js * myPlayer.src("http://www.example.com/path/to/video.mp4"); * ``` * **Source Object (or element):* * A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * ```js * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * ``` * **Array of Source Objects:* * To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * ```js * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * ``` * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting * @method src */ Player.prototype.src = function src(source) { if (source === undefined) { return this.techGet('src'); } var currentTech = _Component3['default'].getComponent(this.techName); // case: Array of source objects to choose from and pick the best to play if (Array.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !currentTech.canPlaySource(source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (currentTech.prototype.hasOwnProperty('setSource')) { this.techCall('setSource', source); } else { this.techCall('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } }); } } return this; }; /** * Handle an array of source objects * * @param {Array} sources Array of source objects * @private * @method sourceList_ */ Player.prototype.sourceList_ = function sourceList_(sources) { var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * * @return {Player} Returns the player * @method load */ Player.prototype.load = function load() { this.techCall('load'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {String} The current source * @method currentSrc */ Player.prototype.currentSrc = function currentSrc() { return this.techGet('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {String} The source MIME type * @method currentType */ Player.prototype.currentType = function currentType() { return this.currentType_ || ''; }; /** * Get or set the preload attribute * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The preload attribute value when getting * @return {Player} Returns the player when setting * @method preload */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall('setPreload', value); this.options_.preload = value; return this; } return this.techGet('preload'); }; /** * Get or set the autoplay attribute. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The autoplay attribute value when getting * @return {Player} Returns the player when setting * @method autoplay */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall('setAutoplay', value); this.options_.autoplay = value; return this; } return this.techGet('autoplay', value); }; /** * Get or set the loop attribute on the video element. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The loop attribute value when getting * @return {Player} Returns the player when setting * @method loop */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall('setLoop', value); this.options_.loop = value; return this; } return this.techGet('loop'); }; /** * get or set the poster image source url * ##### EXAMPLE: * ```js * // get * var currentPoster = myPlayer.poster(); * // set * myPlayer.poster('http://example.com/myImage.jpg'); * ``` * * @param {String=} src Poster image source URL * @return {String} poster URL when getting * @return {Player} self when setting * @method poster */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Get or set whether or not the controls are showing. * * @param {Boolean} bool Set controls to showing or not * @return {Boolean} Controls are showing * @method controls */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners(); } } } return this; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {Player} Returns the player * @private * @method usingNativeControls */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {MediaError|null} when getting * @return {Player} when setting * @method error */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof _MediaError2['default']) { this.error_ = err; } else { this.error_ = new _MediaError2['default'](err); } // fire an error event on the player this.trigger('error'); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _log2['default'].error('(CODE:' + this.error_.code + ' ' + _MediaError2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); return this; }; /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method ended */ Player.prototype.ended = function ended() { return this.techGet('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method seeking */ Player.prototype.seeking = function seeking() { return this.techGet('seeking'); }; /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method seekable */ Player.prototype.seekable = function seekable() { return this.techGet('seekable'); }; /** * Report user activity * * @param {Object} event Event object * @method reportUserActivity */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @param {Boolean} bool Value when setting * @return {Boolean} Value if user is active user when getting * @method userActive */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech) { this.tech.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @method listenForUserActivity */ Player.prototype.listenForUserActivity = function listenForUserActivity() { var mouseInProgress = undefined, lastMoveX = undefined, lastMoveY = undefined; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = undefined; var activityCheck = this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_.inactivityTimeout; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {Number} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting * @method playbackRate */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall('setPlaybackRate', rate); return this; } if (this.tech && this.tech.featuresPlaybackRate) { return this.techGet('playbackRate'); } else { return 1; } }; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {Player} Returns the player if setting * @private * @method isAudio */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return !!this.isAudio_; }; /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {Number} the current network activity state * @method networkState */ Player.prototype.networkState = function networkState() { return this.techGet('networkState'); }; /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {Number} the current playback rendering state * @method readyState */ Player.prototype.readyState = function readyState() { return this.techGet('readyState'); }; /* * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {Array} Array of track objects * @method textTracks */ Player.prototype.textTracks = function textTracks() { // cannot use techGet directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. return this.tech && this.tech.textTracks(); }; /** * Get an array of remote text tracks * * @return {Array} * @method remoteTextTracks */ Player.prototype.remoteTextTracks = function remoteTextTracks() { return this.tech && this.tech.remoteTextTracks(); }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language * @method addTextTrack */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { return this.tech && this.tech.addTextTrack(kind, label, language); }; /** * Add a remote text track * * @param {Object} options Options for remote text track * @method addRemoteTextTrack */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { return this.tech && this.tech.addRemoteTextTrack(options); }; /** * Remove a remote text track * * @param {Object} track Remote text track to remove * @method removeRemoteTextTrack */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.tech && this.tech.removeRemoteTextTrack(track); }; /** * Get video width * * @return {Number} Video width * @method videoWidth */ Player.prototype.videoWidth = function videoWidth() { return this.tech && this.tech.videoWidth && this.tech.videoWidth() || 0; }; /** * Get video height * * @return {Number} Video height * @method videoHeight */ Player.prototype.videoHeight = function videoHeight() { return this.tech && this.tech.videoHeight && this.tech.videoHeight() || 0; }; // Methods to add support for // initialTime: function(){ return this.techCall('initialTime'); }, // startOffsetTime: function(){ return this.techCall('startOffsetTime'); }, // played: function(){ return this.techCall('played'); }, // seekable: function(){ return this.techCall('seekable'); }, // videoTracks: function(){ return this.techCall('videoTracks'); }, // audioTracks: function(){ return this.techCall('audioTracks'); }, // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); }, // mediaGroup: function(){ return this.techCall('mediaGroup'); }, // controller: function(){ return this.techCall('controller'); }, // defaultMuted: function(){ return this.techCall('defaultMuted'); } // TODO // currentSrcList: the array of sources including other formats and bitrates // playList: array of source lists in order of playback /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {String} code The locale string * @return {String} The locale string when getting * @return {Player} self when setting * @method language */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = ('' + code).toLowerCase(); return this; }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} Array of languages * @method languages */ Player.prototype.languages = function languages() { return _mergeOptions2['default'](_globalOptions2['default'].languages, this.languages_); }; /** * Converts track info to JSON * * @return {Object} JSON object of options * @method toJSON */ Player.prototype.toJSON = function toJSON() { var options = _mergeOptions2['default'](this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = _mergeOptions2['default'](track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Gets tag settings * * @param {Element} tag The player tag * @return {Array} An array of sources and track objects * @static * @method getTagSettings */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { sources: [], tracks: [] }; var tagOptions = Dom.getElAttributes(tag); var dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON // If empty string, make it a parsable json object. var _safeParseTuple = _safeParseTuple3['default'](dataSetup || '{}'); var err = _safeParseTuple[0]; var data = _safeParseTuple[1]; if (err) { _log2['default'].error(err); } _assign2['default'](tagOptions, data); } _assign2['default'](baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getElAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getElAttributes(child)); } } } return baseOptions; }; return Player; })(_Component3['default']); /* * Global player list * * @type {Object} */ Player.players = {}; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * All options should use string keys so they avoid * renaming by closure compiler * * @type {Object} * @private */ Player.prototype.options_ = _globalOptions2['default']; /** * Fired when the player has initial duration and dimension information * * @event loadedmetadata */ Player.prototype.handleLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * * @event loadeddata */ Player.prototype.handleLoadedData; /** * Fired when the player has finished downloading the source data * * @event loadedalldata */ Player.prototype.handleLoadedAllData; /** * Fired when the user is active, e.g. moves the mouse over the player * * @event useractive */ Player.prototype.handleUserActive; /** * Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction * * @event userinactive */ Player.prototype.handleUserInactive; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event timeupdate */ Player.prototype.handleTimeUpdate; /** * Fired when the volume changes * * @event volumechange */ Player.prototype.handleVolumeChange; /** * Fired when an error occurs * * @event error */ Player.prototype.handleError; Player.prototype.flexNotSupported_ = function () { var elem = _document2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style /* IE10-specific (2012 flex spec) */); }; _Component3['default'].registerComponent('Player', Player); exports['default'] = Player; module.exports = exports['default']; },{"./big-play-button.js":50,"./component.js":52,"./control-bar/control-bar.js":53,"./error-display.js":82,"./fullscreen-api.js":85,"./global-options.js":86,"./loading-spinner.js":87,"./media-error.js":88,"./poster-image.js":94,"./tech/html5.js":99,"./tech/loader.js":100,"./tracks/text-track-display.js":103,"./tracks/text-track-settings.js":106,"./utils/browser.js":108,"./utils/buffer.js":109,"./utils/dom.js":110,"./utils/events.js":111,"./utils/fn.js":112,"./utils/guid.js":114,"./utils/log.js":115,"./utils/merge-options.js":116,"./utils/time-ranges.js":118,"./utils/to-title-case.js":119,"global/document":1,"global/window":2,"object.assign":44,"safe-json-parse/tuple":49}],93:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file plugins.js */ var _Player = _dereq_('./player.js'); var _Player2 = _interopRequireWildcard(_Player); /** * The method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits * @method plugin */ var plugin = function plugin(name, init) { _Player2['default'].prototype[name] = init; }; exports['default'] = plugin; module.exports = exports['default']; },{"./player.js":92}],94:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file poster-image.js */ var _Button2 = _dereq_('./button.js'); var _Button3 = _interopRequireWildcard(_Button2); var _Component = _dereq_('./component.js'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _import2 = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import2); var _import3 = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_import3); /** * The component that handles showing the poster image. * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PosterImage */ var PosterImage = (function (_Button) { function PosterImage(player, options) { _classCallCheck(this, PosterImage); _Button.call(this, player, options); this.update(); player.on('posterchange', Fn.bind(this, this.update)); } _inherits(PosterImage, _Button); /** * Clean up the poster image * * @method dispose */ PosterImage.prototype.dispose = function dispose() { this.player().off('posterchange', this.update); _Button.prototype.dispose.call(this); }; /** * Create the poster's image element * * @return {Element} * @method createEl */ PosterImage.prototype.createEl = function createEl() { var el = Dom.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!browser.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = Dom.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source * * @method update */ PosterImage.prototype.update = function update() { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the poster source depending on the display method * * @param {String} url The URL to the poster source * @method setSrc */ PosterImage.prototype.setSrc = function setSrc(url) { if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { var backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image * * @method handleClick */ PosterImage.prototype.handleClick = function handleClick() { // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; return PosterImage; })(_Button3['default']); _Component2['default'].registerComponent('PosterImage', PosterImage); exports['default'] = PosterImage; module.exports = exports['default']; },{"./button.js":51,"./component.js":52,"./utils/browser.js":108,"./utils/dom.js":110,"./utils/fn.js":112}],95:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file setup.js * * Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ var _import = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_import); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _windowLoaded = false; var videojs = undefined; // Automatically set up any tags that have a data-setup attribute var autoSetup = function autoSetup() { // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = _document2['default'].getElementsByTagName('video'); var audios = _document2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var i = 0, e = audios.length; i < e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var i = 0, e = mediaEls.length; i < e; i++) { var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl.player === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. var player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; // Pause to let the DOM keep processing var autoSetupTimeout = function autoSetupTimeout(wait, vjs) { videojs = vjs; setTimeout(autoSetup, wait); }; if (_document2['default'].readyState === 'complete') { _windowLoaded = true; } else { Events.one(_window2['default'], 'load', function () { _windowLoaded = true; }); } var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; },{"./utils/events.js":111,"global/document":1,"global/window":2}],96:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file slider.js */ var _Component2 = _dereq_('../component.js'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _roundFloat = _dereq_('../utils/round-float.js'); var _roundFloat2 = _interopRequireWildcard(_roundFloat); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); /** * The base functionality for sliders like the volume bar and seek bar * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class Slider */ var Slider = (function (_Component) { function Slider(player, options) { _classCallCheck(this, Slider); _Component.call(this, player, options); // Set property names to bar and handle to match with the child Slider class is looking for this.bar = this.getChild(this.options_.barName); this.handle = this.getChild(this.options_.handleName); // Set a horizontal or vertical class on the slider depending on the slider type this.vertical(!!this.options_.vertical); this.on('mousedown', this.handleMouseDown); this.on('touchstart', this.handleMouseDown); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); this.on('click', this.handleClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } _inherits(Slider, _Component); /** * Create the component's DOM element * * @param {String} type Type of element to create * @param {Object=} props List of properties in Object form * @return {Element} * @method createEl */ Slider.prototype.createEl = function createEl(type) { var props = arguments[1] === undefined ? {} : arguments[1]; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = _assign2['default']({ role: 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return _Component.prototype.createEl.call(this, type, props); }; /** * Handle mouse down on slider * * @param {Object} event Mouse down event object * @method handleMouseDown */ Slider.prototype.handleMouseDown = function handleMouseDown(event) { event.preventDefault(); Dom.blockTextSelection(); this.addClass('vjs-sliding'); this.on(_document2['default'], 'mousemove', this.handleMouseMove); this.on(_document2['default'], 'mouseup', this.handleMouseUp); this.on(_document2['default'], 'touchmove', this.handleMouseMove); this.on(_document2['default'], 'touchend', this.handleMouseUp); this.handleMouseMove(event); }; /** * To be overridden by a subclass * * @method handleMouseMove */ Slider.prototype.handleMouseMove = function handleMouseMove() {}; /** * Handle mouse up on Slider * * @method handleMouseUp */ Slider.prototype.handleMouseUp = function handleMouseUp() { Dom.unblockTextSelection(); this.removeClass('vjs-sliding'); this.off(_document2['default'], 'mousemove', this.handleMouseMove); this.off(_document2['default'], 'mouseup', this.handleMouseUp); this.off(_document2['default'], 'touchmove', this.handleMouseMove); this.off(_document2['default'], 'touchend', this.handleMouseUp); this.update(); }; /** * Update slider * * @method update */ Slider.prototype.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) { return; } // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) { return; } // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = _roundFloat2['default'](progress * 100, 2) + '%'; // Set the new bar width or height if (this.vertical()) { bar.el().style.height = percentage; } else { bar.el().style.width = percentage; } }; /** * Calculate distance for slider * * @param {Object} event Event object * @method calculateDistance */ Slider.prototype.calculateDistance = function calculateDistance(event) { var el = this.el_; var box = Dom.findElPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var handle = this.handle; if (this.options_.vertical) { var boxY = box.top; var pageY = undefined; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } if (handle) { var handleH = handle.el().offsetHeight; // Adjusted X and Width, so handle doesn't go outside the bar boxY = boxY + handleH / 2; boxH = boxH - handleH; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); } else { var boxX = box.left; var pageX = undefined; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } if (handle) { var handleW = handle.el().offsetWidth; // Adjusted X and Width, so handle doesn't go outside the bar boxX = boxX + handleW / 2; boxW = boxW - handleW; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; /** * Handle on focus for slider * * @method handleFocus */ Slider.prototype.handleFocus = function handleFocus() { this.on(_document2['default'], 'keydown', this.handleKeyPress); }; /** * Handle key press for slider * * @param {Object} event Event object * @method handleKeyPress */ Slider.prototype.handleKeyPress = function handleKeyPress(event) { if (event.which === 37 || event.which === 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which === 38 || event.which === 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; /** * Handle on blur for slider * * @method handleBlur */ Slider.prototype.handleBlur = function handleBlur() { this.off(_document2['default'], 'keydown', this.handleKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event Event object * @method handleClick */ Slider.prototype.handleClick = function handleClick(event) { event.stopImmediatePropagation(); event.preventDefault(); }; /** * Get/set if slider is horizontal for vertical * * @param {Boolean} bool True if slider is vertical, false is horizontal * @return {Boolean} True if slider is vertical, false is horizontal * @method vertical */ Slider.prototype.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } return this; }; return Slider; })(_Component3['default']); _Component3['default'].registerComponent('Slider', Slider); exports['default'] = Slider; module.exports = exports['default']; },{"../component.js":52,"../utils/dom.js":110,"../utils/round-float.js":117,"global/document":1,"object.assign":44}],97:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file flash-rtmp.js */ function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) return parts; // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin = undefined; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid Flash.RTMP_RE = /^rtmp[set]?:\/\//i; Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source) { if (Flash.isStreamingType(source.type) || Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.rtmpSourceHandler.handleSource = function (source, tech) { var srcParts = Flash.streamToParts(source.src); tech.setRtmpConnection(srcParts.connection); tech.setRtmpStream(srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; module.exports = exports['default']; },{}],98:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ var _Tech2 = _dereq_('./tech'); var _Tech3 = _interopRequireWildcard(_Tech2); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_import2); var _createTimeRange = _dereq_('../utils/time-ranges.js'); var _FlashRtmpDecorator = _dereq_('./flash-rtmp'); var _FlashRtmpDecorator2 = _interopRequireWildcard(_FlashRtmpDecorator); var _Component = _dereq_('../component'); var _Component2 = _interopRequireWildcard(_Component); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var navigator = _window2['default'].navigator; /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Flash */ var Flash = (function (_Tech) { function Flash(options, ready) { _classCallCheck(this, Flash); _Tech.call(this, options, ready); // If source was supplied pass as a flash var. if (options.source) { this.ready(function () { this.setSource(options.source); }); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _window2['default'].videojs = _window2['default'].videojs || {}; _window2['default'].videojs.Flash = _window2['default'].videojs.Flash || {}; _window2['default'].videojs.Flash.onReady = Flash.onReady; _window2['default'].videojs.Flash.onEvent = Flash.onEvent; _window2['default'].videojs.Flash.onError = Flash.onError; this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); } _inherits(Flash, _Tech); /** * Create the component's DOM element * * @return {Element} * @method createEl */ Flash.prototype.createEl = function createEl() { var options = this.options_; // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = _assign2['default']({ // SWF Callback Functions readyFunction: 'videojs.Flash.onReady', eventProxyFunction: 'videojs.Flash.onEvent', errorEventProxyFunction: 'videojs.Flash.onError', // Player Settings autoplay: options.autoplay, preload: options.preload, loop: options.loop, muted: options.muted }, options.flashVars); // Merge default parames with ones passed in var params = _assign2['default']({ wmode: 'opaque', // Opaque is needed to overlay controls, but can affect playback performance bgcolor: '#000000' // Using bgcolor prevents a white flash when the object is loading }, options.params); // Merge default attributes with ones passed in var attributes = _assign2['default']({ id: objId, name: objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Play for flash tech * * @method play */ Flash.prototype.play = function play() { this.el_.vjs_play(); }; /** * Pause for flash tech * * @method pause */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Flash.prototype.src = (function (_src) { function src(_x) { return _src.apply(this, arguments); } src.toString = function () { return _src.toString(); }; return src; })(function (src) { if (src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(src); }); /** * Set video * * @param {Object=} src Source object * @deprecated * @method setSrc */ Flash.prototype.setSrc = function setSrc(src) { // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { var tech = this; this.setTimeout(function () { tech.play(); }, 0); } }; /** * Returns true if the tech is currently seeking. * @return {boolean} true if seeking */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Set current time * * @param {Number} time Current time of video * @method setCurrentTime */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get current time * * @param {Number=} time Current time of video * @return {Number} Current time * @method currentTime */ Flash.prototype.currentTime = function currentTime(time) { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get current source * * @method currentSrc */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; /** * Load media into player * * @method load */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get poster * * @method poster */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this a no-op * * @method setPoster */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine if can seek in media * * @return {TimeRangeObject} * @method seekable */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return _createTimeRange.createTimeRange(); } return _createTimeRange.createTimeRange(0, duration); }; /** * Get buffered time range * * @return {TimeRangeObject} * @method buffered */ Flash.prototype.buffered = function buffered() { return _createTimeRange.createTimeRange(0, this.el_.vjs_getProperty('buffered')); }; /** * Get fullscreen support - * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method supportsFullScreen */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { return false; // Flash does not allow fullscreen through javascript }; /** * Request to enter fullscreen * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method enterFullScreen */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; })(_Tech3['default']); // Create setters and getters for attributes var _api = Flash.prototype; var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','); var _readOnly = 'error,networkState,readyState,initialTime,duration,startOffsetTime,paused,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(','); function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var i = 0; i < _readOnly.length; i++) { _createGetter(_readOnly[i]); } /* Flash Support Testing -------------------------------------------------------- */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech _Tech3['default'].withSourceHandlers(Flash); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /* * Check Flash can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canHandleSource = function (source) { var type; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } if (type in Flash.formats) { return 'maybe'; } return ''; }; /* * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; Flash.onReady = function (currSwf) { var el = Dom.getEl(currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash.checkReady(tech); }, 50); } }; // Trigger events from the swf on the player Flash.onEvent = function (swfID, eventName) { var tech = Dom.getEl(swfID).tech; tech.trigger(eventName); }; // Log errors from the swf Flash.onError = function (swfID, err) { var tech = Dom.getEl(swfID).tech; var msg = 'FLASH: ' + err; if (err === 'srcnotfound') { tech.trigger('error', { code: 4, message: msg }); // errors we haven't categorized into the media errors } else { tech.trigger('error', msg); } }; // Flash Version Check Flash.version = function () { var version = '0,0,0'; // IE try { version = new _window2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += '' + key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = _assign2['default']({ movie: swf, flashvars: flashVarsString, allowScriptAccess: 'always', // Required to talk to swf allowNetworking: 'all' // All should be default, but having security issues. }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = _assign2['default']({ // Add swf to attributes (need both for IE and Others to work) data: swf, // Default to 100% width/height width: '100%', height: '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += '' + key + '="' + attributes[key] + '" '; }); return '' + objTag + '' + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator _FlashRtmpDecorator2['default'](Flash); _Component2['default'].registerComponent('Flash', Flash); exports['default'] = Flash; module.exports = exports['default']; },{"../component":52,"../utils/dom.js":110,"../utils/time-ranges.js":118,"../utils/url.js":120,"./flash-rtmp":97,"./tech":101,"global/window":2,"object.assign":44}],99:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file html5.js * HTML5 Media Controller - Wrapper for HTML5 Media API */ var _Tech2 = _dereq_('./tech.js'); var _Tech3 = _interopRequireWildcard(_Tech2); var _Component = _dereq_('../component'); var _Component2 = _interopRequireWildcard(_Component); var _import = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_import2); var _import3 = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import3); var _log = _dereq_('../utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _import4 = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_import4); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var _mergeOptions = _dereq_('../utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Html5 */ var Html5 = (function (_Tech) { function Html5(options, ready) { _classCallCheck(this, Html5); _Tech.call(this, options, ready); var source = options.source; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { this.setSource(source); } if (this.el_.hasChildNodes()) { var nodes = this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { this.remoteTextTracks().addTrack_(node.track); } } } for (var i = 0; i < removeNodes.length; i++) { this.el_.removeChild(removeNodes[i]); } } if (this.featuresNativeTextTracks) { this.on('loadstart', Fn.bind(this, this.hideCaptions)); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true) { this.trigger('usenativecontrols'); } this.triggerReady(); } _inherits(Html5, _Tech); /** * Dispose of html5 media element * * @method dispose */ Html5.prototype.dispose = function dispose() { Html5.disposeMediaElement(this.el_); _Tech.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Html5.prototype.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this.movingMediaElementInDOM === false) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(false); el.parentNode.insertBefore(clone, el); Html5.disposeMediaElement(el); el = clone; } else { el = _document2['default'].createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag); var attributes = _mergeOptions2['default']({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setElAttributes(el, _assign2['default'](attributes, { id: this.options_.techId, 'class': 'vjs-tech' })); } if (this.options_.tracks) { for (var i = 0; i < this.options_.tracks.length; i++) { var _track = this.options_.tracks[i]; var trackEl = _document2['default'].createElement('track'); trackEl.kind = _track.kind; trackEl.label = _track.label; trackEl.srclang = _track.srclang; trackEl.src = _track.src; if ('default' in _track) { trackEl.setAttribute('default', 'default'); } el.appendChild(trackEl); } } } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setElAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; /** * Hide captions from text track * * @method hideCaptions */ Html5.prototype.hideCaptions = function hideCaptions() { var tracks = this.el_.querySelectorAll('track'); var i = tracks.length; var kinds = { captions: 1, subtitles: 1 }; while (i--) { var _track2 = tracks[i].track; if (_track2 && _track2.kind in kinds && !tracks[i]['default']) { _track2.mode = 'disabled'; } } }; /** * Play for html5 tech * * @method play */ Html5.prototype.play = function play() { this.el_.play(); }; /** * Pause for html5 tech * * @method pause */ Html5.prototype.pause = function pause() { this.el_.pause(); }; /** * Paused for html5 tech * * @return {Boolean} * @method paused */ Html5.prototype.paused = function paused() { return this.el_.paused; }; /** * Get current time * * @return {Number} * @method currentTime */ Html5.prototype.currentTime = function currentTime() { return this.el_.currentTime; }; /** * Set current time * * @param {Number} seconds Current time of video * @method setCurrentTime */ Html5.prototype.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { _log2['default'](e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; /** * Get duration * * @return {Number} * @method duration */ Html5.prototype.duration = function duration() { return this.el_.duration || 0; }; /** * Get a TimeRange object that represents the intersection * of the time ranges for which the user agent has all * relevant media * * @return {TimeRangeObject} * @method buffered */ Html5.prototype.buffered = function buffered() { return this.el_.buffered; }; /** * Get volume level * * @return {Number} * @method volume */ Html5.prototype.volume = function volume() { return this.el_.volume; }; /** * Set volume level * * @param {Number} percentAsDecimal Volume percent as a decimal * @method setVolume */ Html5.prototype.setVolume = function setVolume(percentAsDecimal) { this.el_.volume = percentAsDecimal; }; /** * Get if muted * * @return {Boolean} * @method muted */ Html5.prototype.muted = function muted() { return this.el_.muted; }; /** * Set muted * * @param {Boolean} If player is to be muted or note * @method setMuted */ Html5.prototype.setMuted = function setMuted(muted) { this.el_.muted = muted; }; /** * Get player width * * @return {Number} * @method width */ Html5.prototype.width = function width() { return this.el_.offsetWidth; }; /** * Get player height * * @return {Number} * @method height */ Html5.prototype.height = function height() { return this.el_.offsetHeight; }; /** * Get if there is fullscreen support * * @return {Boolean} * @method supportsFullScreen */ Html5.prototype.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = _window2['default'].navigator.userAgent; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; }; /** * Request to enter fullscreen * * @method enterFullScreen */ Html5.prototype.enterFullScreen = function enterFullScreen() { var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function () { this.one('webkitendfullscreen', function () { this.trigger('fullscreenchange', { isFullscreen: false }); }); this.trigger('fullscreenchange', { isFullscreen: true }); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; /** * Request to exit fullscreen * * @method exitFullScreen */ Html5.prototype.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Html5.prototype.src = (function (_src) { function src(_x) { return _src.apply(this, arguments); } src.toString = function () { return _src.toString(); }; return src; })(function (src) { if (src === undefined) { return this.el_.src; } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(src); } }); /** * Set video * * @param {Object} src Source object * @deprecated * @method setSrc */ Html5.prototype.setSrc = function setSrc(src) { this.el_.src = src; }; /** * Load media into player * * @method load */ Html5.prototype.load = function load() { this.el_.load(); }; /** * Get current source * * @return {Object} * @method currentSrc */ Html5.prototype.currentSrc = function currentSrc() { return this.el_.currentSrc; }; /** * Get poster * * @return {String} * @method poster */ Html5.prototype.poster = function poster() { return this.el_.poster; }; /** * Set poster * * @param {String} val URL to poster image * @method */ Html5.prototype.setPoster = function setPoster(val) { this.el_.poster = val; }; /** * Get preload attribute * * @return {String} * @method preload */ Html5.prototype.preload = function preload() { return this.el_.preload; }; /** * Set preload attribute * * @param {String} val Value for preload attribute * @method setPreload */ Html5.prototype.setPreload = function setPreload(val) { this.el_.preload = val; }; /** * Get autoplay attribute * * @return {String} * @method autoplay */ Html5.prototype.autoplay = function autoplay() { return this.el_.autoplay; }; /** * Set autoplay attribute * * @param {String} val Value for preload attribute * @method setAutoplay */ Html5.prototype.setAutoplay = function setAutoplay(val) { this.el_.autoplay = val; }; /** * Get controls attribute * * @return {String} * @method controls */ Html5.prototype.controls = function controls() { return this.el_.controls; }; /** * Set controls attribute * * @param {String} val Value for controls attribute * @method setControls */ Html5.prototype.setControls = function setControls(val) { this.el_.controls = !!val; }; /** * Get loop attribute * * @return {String} * @method loop */ Html5.prototype.loop = function loop() { return this.el_.loop; }; /** * Set loop attribute * * @param {String} val Value for loop attribute * @method setLoop */ Html5.prototype.setLoop = function setLoop(val) { this.el_.loop = val; }; /** * Get error value * * @return {String} * @method error */ Html5.prototype.error = function error() { return this.el_.error; }; /** * Get whether or not the player is in the "seeking" state * * @return {Boolean} * @method seeking */ Html5.prototype.seeking = function seeking() { return this.el_.seeking; }; /** * Get a TimeRanges object that represents the * ranges of the media resource to which it is possible * for the user agent to seek. * * @return {TimeRangeObject} * @method seekable */ Html5.prototype.seekable = function seekable() { return this.el_.seekable; }; /** * Get if video ended * * @return {Boolean} * @method ended */ Html5.prototype.ended = function ended() { return this.el_.ended; }; /** * Get the value of the muted content attribute * This attribute has no dynamic effect, it only * controls the default state of the element * * @return {Boolean} * @method defaultMuted */ Html5.prototype.defaultMuted = function defaultMuted() { return this.el_.defaultMuted; }; /** * Get desired speed at which the media resource is to play * * @return {Number} * @method playbackRate */ Html5.prototype.playbackRate = function playbackRate() { return this.el_.playbackRate; }; /** * Returns a TimeRanges object that represents the ranges of the * media resource that the user agent has played. * @return {TimeRangeObject} the range of points on the media * timeline that has been reached through normal playback * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played */ Html5.prototype.played = function played() { return this.el_.played; }; /** * Set desired speed at which the media resource is to play * * @param {Number} val Speed at which the media resource is to play * @method setPlaybackRate */ Html5.prototype.setPlaybackRate = function setPlaybackRate(val) { this.el_.playbackRate = val; }; /** * Get the current state of network activity for the element, from * the list below * NETWORK_EMPTY (numeric value 0) * NETWORK_IDLE (numeric value 1) * NETWORK_LOADING (numeric value 2) * NETWORK_NO_SOURCE (numeric value 3) * * @return {Number} * @method networkState */ Html5.prototype.networkState = function networkState() { return this.el_.networkState; }; /** * Get a value that expresses the current state of the element * with respect to rendering the current playback position, from * the codes in the list below * HAVE_NOTHING (numeric value 0) * HAVE_METADATA (numeric value 1) * HAVE_CURRENT_DATA (numeric value 2) * HAVE_FUTURE_DATA (numeric value 3) * HAVE_ENOUGH_DATA (numeric value 4) * * @return {Number} * @method readyState */ Html5.prototype.readyState = function readyState() { return this.el_.readyState; }; /** * Get width of video * * @return {Number} * @method videoWidth */ Html5.prototype.videoWidth = function videoWidth() { return this.el_.videoWidth; }; /** * Get height of video * * @return {Number} * @method videoHeight */ Html5.prototype.videoHeight = function videoHeight() { return this.el_.videoHeight; }; /** * Get text tracks * * @return {TextTrackList} * @method textTracks */ Html5.prototype.textTracks = function textTracks() { if (!this.featuresNativeTextTracks) { return _Tech.prototype.textTracks.call(this); } return this.el_.textTracks; }; /** * Creates and returns a text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments[0] === undefined ? {} : arguments[0]; if (!this.featuresNativeTextTracks) { return _Tech.prototype.addRemoteTextTrack.call(this, options); } var track = _document2['default'].createElement('track'); if (options.kind) { track.kind = options.kind; } if (options.label) { track.label = options.label; } if (options.language || options.srclang) { track.srclang = options.language || options.srclang; } if (options['default']) { track['default'] = options['default']; } if (options.id) { track.id = options.id; } if (options.src) { track.src = options.src; } this.el().appendChild(track); if (track.track.kind === 'metadata') { track.track.mode = 'hidden'; } else { track.track.mode = 'disabled'; } track.onload = function () { var tt = track.track; if (track.readyState >= 2) { if (tt.kind === 'metadata' && tt.mode !== 'hidden') { tt.mode = 'hidden'; } else if (tt.kind !== 'metadata' && tt.mode !== 'disabled') { tt.mode = 'disabled'; } track.onload = null; } }; this.remoteTextTracks().addTrack_(track.track); return track; }; /** * Remove remote text track from TextTrackList object * * @param {TextTrackObject} track Texttrack object to remove * @method removeRemoteTextTrack */ Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { if (!this.featuresNativeTextTracks) { return _Tech.prototype.removeRemoteTextTrack.call(this, track); } var tracks, i; this.remoteTextTracks().removeTrack_(track); tracks = this.el().querySelectorAll('track'); for (i = 0; i < tracks.length; i++) { if (tracks[i] === track || tracks[i].track === track) { tracks[i].parentNode.removeChild(tracks[i]); break; } } }; return Html5; })(_Tech3['default']); /* HTML5 Support Testing ---------------------------------------------------- */ /* * Element for testing browser HTML5 video capabilities * * @type {Element} * @constant * @private */ Html5.TEST_VID = _document2['default'].createElement('video'); var track = _document2['default'].createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); /* * Check if HTML5 video is supported by this browser/device * * @return {Boolean} */ Html5.isSupported = function () { // IE9 with no Media Player is a LIAR! (#984) try { Html5.TEST_VID.volume = 0.5; } catch (e) { return false; } return !!Html5.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech _Tech3['default'].withSourceHandlers(Html5); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Html5} tech The instance of the HTML5 tech */ Html5.nativeSourceHandler = {}; /* * Check if the video element can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canHandleSource = function (source) { var match, ext; function canPlayType(type) { // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } } // If a type was provided we should rely on that if (source.type) { return canPlayType(source.type); } else if (source.src) { // If no type, fall back to checking 'video/[EXTENSION]' ext = Url.getFileExtension(source.src); return canPlayType('video/' + ext); } return ''; }; /* * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Html5} tech The instance of the Html5 tech */ Html5.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); /* * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {Boolean} */ Html5.canControlVolume = function () { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; }; /* * Check if playbackRate is supported in this browser/device. * * @return {Number} [description] */ Html5.canControlPlaybackRate = function () { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; }; /* * Check to see if native text tracks are supported by this browser/device * * @return {Boolean} */ Html5.supportsNativeTextTracks = function () { var supportsTextTracks; // Figure out native text track support // If mode is a number, we cannot change it because it'll disappear from view. // Browsers with numeric modes include IE10 and older (<=2013) samsung android models. // Firefox isn't playing nice either with modifying the mode // TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862 supportsTextTracks = !!Html5.TEST_VID.textTracks; if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) { supportsTextTracks = typeof Html5.TEST_VID.textTracks[0].mode !== 'number'; } if (supportsTextTracks && browser.IS_FIREFOX) { supportsTextTracks = false; } return supportsTextTracks; }; /* * Set the tech's volume control support status * * @type {Boolean} */ Html5.prototype.featuresVolumeControl = Html5.canControlVolume(); /* * Set the tech's playbackRate support status * * @type {Boolean} */ Html5.prototype.featuresPlaybackRate = Html5.canControlPlaybackRate(); /* * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * * @type {Boolean} */ Html5.prototype.movingMediaElementInDOM = !browser.IS_IOS; /* * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ Html5.prototype.featuresFullscreenResize = true; /* * Set the tech's progress event support status * (this disables the manual progress events of the Tech) */ Html5.prototype.featuresProgressEvents = true; /* * Sets the tech's status on native text track support * * @type {Boolean} */ Html5.prototype.featuresNativeTextTracks = Html5.supportsNativeTextTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = undefined; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; var mp4RE = /^video\/mp4/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (browser.ANDROID_VERSION >= 4) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (browser.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) {} })(); } }; _Component2['default'].registerComponent('Html5', Html5); exports['default'] = Html5; module.exports = exports['default']; // not supported },{"../component":52,"../utils/browser.js":108,"../utils/dom.js":110,"../utils/fn.js":112,"../utils/log.js":115,"../utils/merge-options.js":116,"../utils/url.js":120,"./tech.js":101,"global/document":1,"global/window":2,"object.assign":44}],100:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file loader.js */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _toTitleCase = _dereq_('../utils/to-title-case.js'); var _toTitleCase2 = _interopRequireWildcard(_toTitleCase); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class MediaLoader */ var MediaLoader = (function (_Component) { function MediaLoader(player, options, ready) { _classCallCheck(this, MediaLoader); _Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) { for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) { var techName = _toTitleCase2['default'](j[i]); var tech = _Component3['default'].getComponent(techName); // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(options.playerOptions.sources); } } _inherits(MediaLoader, _Component); return MediaLoader; })(_Component3['default']); _Component3['default'].registerComponent('MediaLoader', MediaLoader); exports['default'] = MediaLoader; module.exports = exports['default']; },{"../component":52,"../utils/to-title-case.js":119,"global/window":2}],101:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file tech.js * Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _TextTrack = _dereq_('../tracks/text-track'); var _TextTrack2 = _interopRequireWildcard(_TextTrack); var _TextTrackList = _dereq_('../tracks/text-track-list'); var _TextTrackList2 = _interopRequireWildcard(_TextTrackList); var _import = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _log = _dereq_('../utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _createTimeRange = _dereq_('../utils/time-ranges.js'); var _bufferedPercent2 = _dereq_('../utils/buffer.js'); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /** * Base class for media (HTML5 Video, Flash) controllers * * @param {Object=} options Options object * @param {Function=} ready Ready callback function * @extends Component * @class Tech */ var Tech = (function (_Component) { function Tech() { var options = arguments[0] === undefined ? {} : arguments[0]; var ready = arguments[1] === undefined ? function () {} : arguments[1]; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; _Component.call(this, null, options, ready); // keep track of whether the current source has played at all to // implement a very limited played() this.hasStarted_ = false; this.on('playing', function () { this.hasStarted_ = true; }); this.on('loadstart', function () { this.hasStarted_ = false; }); this.textTracks_ = options.textTracks; // Manually track progress in cases where the browser/flash player doesn't report it. if (!this.featuresProgressEvents) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this.featuresTimeupdateEvents) { this.manualTimeUpdatesOn(); } this.initControlsListeners(); if (options.nativeCaptions === false || options.nativeTextTracks === false) { this.featuresNativeTextTracks = false; } if (!this.featuresNativeTextTracks) { this.emulateTextTracks(); } this.initTextTrackListeners(); // Turn on component tap events this.emitTapEvents(); } _inherits(Tech, _Component); /** * Set up click and touch listeners for the playback element * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold on * any controls will still keep the user active * * @method initControlsListeners */ Tech.prototype.initControlsListeners = function initControlsListeners() { // if we're loading the playback object after it has started loading or playing the // video (often with autoplay on) then the loadstart event has already fired and we // need to fire it manually because many things rely on it. // Long term we might consider how we would do this for other events like 'canplay' // that may also have fired. this.ready(function () { if (this.networkState && this.networkState() > 0) { this.trigger('loadstart'); } }); }; /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events /** * Turn on progress events * * @method manualProgressOn */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off progress events * * @method manualProgressOff */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * Track progress * * @method trackProgress */ Tech.prototype.trackProgress = function trackProgress() { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update duration * * @method onDurationChange */ Tech.prototype.onDurationChange = function onDurationChange() { this.duration_ = this.duration(); }; /** * Create and get TimeRange object for buffering * * @return {TimeRangeObject} * @method buffered */ Tech.prototype.buffered = function buffered() { return _createTimeRange.createTimeRange(0, 0); }; /** * Get buffered percent * * @return {Number} * @method bufferedPercent */ Tech.prototype.bufferedPercent = (function (_bufferedPercent) { function bufferedPercent() { return _bufferedPercent.apply(this, arguments); } bufferedPercent.toString = function () { return _bufferedPercent.toString(); }; return bufferedPercent; })(function () { return _bufferedPercent2.bufferedPercent(this.buffered(), this.duration_); }); /** * Stops tracking progress by clearing progress interval * * @method stopTrackingProgress */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ /** * Set event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOn */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Remove event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOff */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Tracks current time * * @method trackCurrentTime */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; /** * Turn off play progress tracking (when paused or dragging) * * @method stopTrackingCurrentTime */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off any manual progress or timeupdate tracking * * @method dispose */ Tech.prototype.dispose = function dispose() { // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * Return the time ranges that have been played through for the * current source. This implementation is incomplete. It does not * track the played time ranges, only whether the source has played * at all or not. * @return {TimeRangeObject} a single time range if this video has * played or an empty set of ranges if not. * @method played */ Tech.prototype.played = function played() { if (this.hasStarted_) { return _createTimeRange.createTimeRange(0, 0); } return _createTimeRange.createTimeRange(); }; /** * Set current time * * @method setCurrentTime */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Initialize texttrack listeners * * @method initTextTrackListeners */ Tech.prototype.initTextTrackListeners = function initTextTrackListeners() { var textTrackListChanges = Fn.bind(this, function () { this.trigger('texttrackchange'); }); var tracks = this.textTracks(); if (!tracks) { return; }tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', Fn.bind(this, function () { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; /** * Emulate texttracks * * @method emulateTextTracks */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { if (!_window2['default'].WebVTT && this.el().parentNode != null) { var script = _document2['default'].createElement('script'); script.src = this.options_['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js'; this.el().parentNode.appendChild(script); _window2['default'].WebVTT = true; } var tracks = this.textTracks(); if (!tracks) { return; } var textTracksChanges = Fn.bind(this, function () { var _this = this; var updateDisplay = function updateDisplay() { return _this.trigger('texttrackchange'); }; updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }); tracks.addEventListener('change', textTracksChanges); this.on('dispose', function () { tracks.removeEventListener('change', textTracksChanges); }); }; /* * Provide default methods for text tracks. * * Html5 tech overrides these. */ /** * Get texttracks * * @returns {TextTrackList} * @method textTracks */ Tech.prototype.textTracks = function textTracks() { this.textTracks_ = this.textTracks_ || new _TextTrackList2['default'](); return this.textTracks_; }; /** * Get remote texttracks * * @returns {TextTrackList} * @method remoteTextTracks */ Tech.prototype.remoteTextTracks = function remoteTextTracks() { this.remoteTextTracks_ = this.remoteTextTracks_ || new _TextTrackList2['default'](); return this.remoteTextTracks_; }; /** * Creates and returns a remote text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { var track = createTrackHelper(this, options.kind, options.label, options.language, options); this.remoteTextTracks().addTrack_(track); return { track: track }; }; /** * Remove remote texttrack * * @param {TextTrackObject} track Texttrack to remove * @method removeRemoteTextTrack */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.textTracks().removeTrack_(track); this.remoteTextTracks().removeTrack_(track); }; /** * Provide a default setPoster method for techs * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. * * @method setPoster */ Tech.prototype.setPoster = function setPoster() {}; return Tech; })(_Component3['default']); /* * List of associated text tracks * * @type {Array} * @private */ Tech.prototype.textTracks_; var createTrackHelper = function createTrackHelper(self, kind, label, language) { var options = arguments[4] === undefined ? {} : arguments[4]; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new _TextTrack2['default'](options); tracks.addTrack_(track); return track; }; Tech.prototype.featuresVolumeControl = true; // Resizing plugins using request fullscreen reloads the plugin Tech.prototype.featuresFullscreenResize = false; Tech.prototype.featuresPlaybackRate = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf Tech.prototype.featuresProgressEvents = false; Tech.prototype.featuresTimeupdateEvents = false; Tech.prototype.featuresNativeTextTracks = false; /* * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * Tech.withSourceHandlers.call(MyTech); * */ Tech.withSourceHandlers = function (_Tech) { /* * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /* * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ _Tech.selectSourceHandler = function (source) { var handlers = _Tech.sourceHandlers || []; var can = undefined; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /* * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj) { var sh = _Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; /* * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {Tech} self */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { _log2['default'].error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); this.originalSeekable_ = this.seekable; // when a source handler is registered, prefer its implementation of // seekable when present. this.seekable = function () { if (this.sourceHandler_ && this.sourceHandler_.seekable) { return this.sourceHandler_.seekable(); } return this.originalSeekable_.call(this); }; return this; }; /* * Clean up any existing source handler */ _Tech.prototype.disposeSourceHandler = function () { if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); this.seekable = this.originalSeekable_; } }; }; _Component3['default'].registerComponent('Tech', Tech); // Old name for Tech _Component3['default'].registerComponent('MediaTechController', Tech); exports['default'] = Tech; module.exports = exports['default']; },{"../component":52,"../tracks/text-track":107,"../tracks/text-track-list":105,"../utils/buffer.js":109,"../utils/fn.js":112,"../utils/log.js":115,"../utils/time-ranges.js":118,"global/document":1,"global/window":2}],102:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file text-track-cue-list.js */ var _import = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_import); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist * * interface TextTrackCueList { * readonly attribute unsigned long length; * getter TextTrackCue (unsigned long index); * TextTrackCue? getCueById(DOMString id); * }; */ var TextTrackCueList = (function (_TextTrackCueList) { function TextTrackCueList(_x) { return _TextTrackCueList.apply(this, arguments); } TextTrackCueList.toString = function () { return _TextTrackCueList.toString(); }; return TextTrackCueList; })(function (cues) { var list = this; if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in TextTrackCueList.prototype) { list[prop] = TextTrackCueList.prototype[prop]; } } TextTrackCueList.prototype.setCues_.call(list, cues); Object.defineProperty(list, 'length', { get: function get() { return this.length_; } }); if (browser.IS_IE8) { return list; } }); TextTrackCueList.prototype.setCues_ = function (cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(i) { if (!('' + i in this)) { Object.defineProperty(this, '' + i, { get: function get() { return this.cues_[i]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } }; TextTrackCueList.prototype.getCueById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; exports['default'] = TextTrackCueList; module.exports = exports['default']; },{"../utils/browser.js":108,"global/document":1}],103:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file text-track-display.js */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _Menu = _dereq_('../menu/menu.js'); var _Menu2 = _interopRequireWildcard(_Menu); var _MenuItem = _dereq_('../menu/menu-item.js'); var _MenuItem2 = _interopRequireWildcard(_MenuItem); var _MenuButton = _dereq_('../menu/menu-button.js'); var _MenuButton2 = _interopRequireWildcard(_MenuButton); var _import = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * The component for displaying text track cues * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class TextTrackDisplay */ var TextTrackDisplay = (function (_Component) { function TextTrackDisplay(player, options, ready) { _classCallCheck(this, TextTrackDisplay); _Component.call(this, player, options, ready); player.on('loadstart', Fn.bind(this, this.toggleDisplay)); player.on('texttrackchange', Fn.bind(this, this.updateDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(Fn.bind(this, function () { if (player.tech && player.tech.featuresNativeTextTracks) { this.hide(); return; } player.on('fullscreenchange', Fn.bind(this, this.updateDisplay)); var tracks = this.options_.playerOptions.tracks || []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; this.player_.addRemoteTextTrack(track); } })); } _inherits(TextTrackDisplay, _Component); /** * Toggle display texttracks * * @method toggleDisplay */ TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() { if (this.player_.tech && this.player_.tech.featuresNativeTextTracks) { this.hide(); } else { this.show(); } }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * Clear display texttracks * * @method clearDisplay */ TextTrackDisplay.prototype.clearDisplay = function clearDisplay() { if (typeof _window2['default'].WebVTT === 'function') { _window2['default'].WebVTT.processCues(_window2['default'], [], this.el_); } }; /** * Update display texttracks * * @method updateDisplay */ TextTrackDisplay.prototype.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); this.clearDisplay(); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track.mode === 'showing') { this.updateForTrack(track); } } }; /** * Add texttrack to texttrack list * * @param {TextTrackObject} track Texttrack object to be added to list * @method updateForTrack */ TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) { if (typeof _window2['default'].WebVTT !== 'function' || !track.activeCues) { return; } var overrides = this.player_.textTrackSettings.getValues(); var cues = []; for (var _i = 0; _i < track.activeCues.length; _i++) { cues.push(track.activeCues[_i]); } _window2['default'].WebVTT.processCues(_window2['default'], track.activeCues, this.el_); var i = cues.length; while (i--) { var cueDiv = cues[i].displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = _window2['default'].parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; return TextTrackDisplay; })(_Component3['default']); /** * Add cue HTML to display * * @param {Number} color Hex number for color, like #f0e * @param {Number} opacity Value for opacity,0.0 - 1.0 * @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)' * @method constructColor */ function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; } /** * Try to update style * Some style changes will throw an error, particularly in IE8. Those should be noops. * * @param {Element} el The element to be styles * @param {CSSProperty} style The CSS property to be styled * @param {CSSStyle} rule The actual style to be applied to the property * @method tryUpdateStyle */ function tryUpdateStyle(el, style, rule) { // try { el.style[style] = rule; } catch (e) {} } _Component3['default'].registerComponent('TextTrackDisplay', TextTrackDisplay); exports['default'] = TextTrackDisplay; module.exports = exports['default']; },{"../component":52,"../menu/menu-button.js":89,"../menu/menu-item.js":90,"../menu/menu.js":91,"../utils/fn.js":112,"global/document":1,"global/window":2}],104:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file text-track-enums.js * * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * * enum TextTrackMode { "disabled", "hidden", "showing" }; */ var TextTrackMode = { disabled: 'disabled', hidden: 'hidden', showing: 'showing' }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind * * enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" }; */ var TextTrackKind = { subtitles: 'subtitles', captions: 'captions', descriptions: 'descriptions', chapters: 'chapters', metadata: 'metadata' }; exports.TextTrackMode = TextTrackMode; exports.TextTrackKind = TextTrackKind; },{}],105:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file text-track-list.js */ var _EventEmitter = _dereq_('../event-emitter'); var _EventEmitter2 = _interopRequireWildcard(_EventEmitter); var _import = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_import2); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist * * interface TextTrackList : EventTarget { * readonly attribute unsigned long length; * getter TextTrack (unsigned long index); * TextTrack? getTrackById(DOMString id); * * attribute EventHandler onchange; * attribute EventHandler onaddtrack; * attribute EventHandler onremovetrack; * }; */ var TextTrackList = (function (_TextTrackList) { function TextTrackList(_x) { return _TextTrackList.apply(this, arguments); } TextTrackList.toString = function () { return _TextTrackList.toString(); }; return TextTrackList; })(function (tracks) { var list = this; if (browser.IS_IE8) { list = _document2['default'].createElement('custom'); for (var prop in TextTrackList.prototype) { list[prop] = TextTrackList.prototype[prop]; } } tracks = tracks || []; list.tracks_ = []; Object.defineProperty(list, 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { list.addTrack_(tracks[i]); } if (browser.IS_IE8) { return list; } }); TextTrackList.prototype = Object.create(_EventEmitter2['default'].prototype); TextTrackList.prototype.constructor = TextTrackList; /* * change - One or more tracks in the track list have been enabled or disabled. * addtrack - A track has been added to the track list. * removetrack - A track has been removed from the track list. */ TextTrackList.prototype.allowedEvents_ = { change: 'change', addtrack: 'addtrack', removetrack: 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var _event in TextTrackList.prototype.allowedEvents_) { TextTrackList.prototype['on' + _event] = null; } TextTrackList.prototype.addTrack_ = function (track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } track.addEventListener('modechange', Fn.bind(this, function () { this.trigger('change'); })); this.tracks_.push(track); this.trigger({ type: 'addtrack', track: track }); }; TextTrackList.prototype.removeTrack_ = function (rtrack) { var result = null; var track = undefined; for (var i = 0, l = this.length; i < l; i++) { track = this[i]; if (track === rtrack) { this.tracks_.splice(i, 1); break; } } this.trigger({ type: 'removetrack', track: track }); }; TextTrackList.prototype.getTrackById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; exports['default'] = TextTrackList; module.exports = exports['default']; },{"../event-emitter":83,"../utils/browser.js":108,"../utils/fn.js":112,"global/document":1}],106:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; exports.__esModule = true; /** * @file text-track-settings.js */ var _Component2 = _dereq_('../component'); var _Component3 = _interopRequireWildcard(_Component2); var _import = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _log = _dereq_('../utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _safeParseTuple2 = _dereq_('safe-json-parse/tuple'); var _safeParseTuple3 = _interopRequireWildcard(_safeParseTuple2); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); /** * Manipulate settings of texttracks * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class TextTrackSettings */ var TextTrackSettings = (function (_Component) { function TextTrackSettings(player, options) { _classCallCheck(this, TextTrackSettings); _Component.call(this, player, options); this.hide(); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings; } Events.on(this.el().querySelector('.vjs-done-button'), 'click', Fn.bind(this, function () { this.saveSettings(); this.hide(); })); Events.on(this.el().querySelector('.vjs-default-button'), 'click', Fn.bind(this, function () { this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0; this.el().querySelector('.window-color > select').selectedIndex = 0; this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-edge-style select').selectedIndex = 0; this.el().querySelector('.vjs-font-family select').selectedIndex = 0; this.el().querySelector('.vjs-font-percent select').selectedIndex = 2; this.updateDisplay(); })); Events.on(this.el().querySelector('.vjs-fg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay)); if (this.options_.persistTextTrackSettings) { this.restoreSettings(); } } _inherits(TextTrackSettings, _Component); /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackSettings.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-caption-settings vjs-modal-overlay', innerHTML: captionOptionsMenuTemplate() }); }; /** * Get texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @return {Object} * @method getValues */ TextTrackSettings.prototype.getValues = function getValues() { var el = this.el(); var textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select')); var fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select')); var fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select')); var textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select')); var bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select')); var bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select')); var windowColor = getSelectedOptionValue(el.querySelector('.window-color > select')); var windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select')); var fontPercent = _window2['default'].parseFloat(getSelectedOptionValue(el.querySelector('.vjs-font-percent > select'))); var result = { backgroundOpacity: bgOpacity, textOpacity: textOpacity, windowOpacity: windowOpacity, edgeStyle: textEdge, fontFamily: fontFamily, color: fgColor, backgroundColor: bgColor, windowColor: windowColor, fontPercent: fontPercent }; for (var _name in result) { if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1) { delete result[_name]; } } return result; }; /** * Set texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @param {Object} values Object with texttrack setting values * @method setValues */ TextTrackSettings.prototype.setValues = function setValues(values) { var el = this.el(); setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle); setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily); setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color); setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity); setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor); setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity); setSelectedOption(el.querySelector('.window-color > select'), values.windowColor); setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity); var fontPercent = values.fontPercent; if (fontPercent) { fontPercent = fontPercent.toFixed(2); } setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent); }; /** * Restore texttrack settings * * @method restoreSettings */ TextTrackSettings.prototype.restoreSettings = function restoreSettings() { var _safeParseTuple = _safeParseTuple3['default'](_window2['default'].localStorage.getItem('vjs-text-track-settings')); var err = _safeParseTuple[0]; var values = _safeParseTuple[1]; if (err) { _log2['default'].error(err); } if (values) { this.setValues(values); } }; /** * Save texttrack settings to local storage * * @method saveSettings */ TextTrackSettings.prototype.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.getOwnPropertyNames(values).length > 0) { _window2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values)); } else { _window2['default'].localStorage.removeItem('vjs-text-track-settings'); } } catch (e) {} }; /** * Update display of texttrack settings * * @method updateDisplay */ TextTrackSettings.prototype.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; return TextTrackSettings; })(_Component3['default']); _Component3['default'].registerComponent('TextTrackSettings', TextTrackSettings); function getSelectedOptionValue(target) { var selectedOption = undefined; // not all browsers support selectedOptions, so, fallback to options if (target.selectedOptions) { selectedOption = target.selectedOptions[0]; } else if (target.options) { selectedOption = target.options[target.options.selectedIndex]; } return selectedOption.value; } function setSelectedOption(target, value) { if (!value) { return; } var i = undefined; for (i = 0; i < target.options.length; i++) { var option = target.options[i]; if (option.value === value) { break; } } target.selectedIndex = i; } function captionOptionsMenuTemplate() { var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>'; return template; } exports['default'] = TextTrackSettings; module.exports = exports['default']; },{"../component":52,"../utils/events.js":111,"../utils/fn.js":112,"../utils/log.js":115,"global/window":2,"safe-json-parse/tuple":49}],107:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file text-track.js */ var _TextTrackCueList = _dereq_('./text-track-cue-list'); var _TextTrackCueList2 = _interopRequireWildcard(_TextTrackCueList); var _import = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_import); var _import2 = _dereq_('../utils/guid.js'); var Guid = _interopRequireWildcard(_import2); var _import3 = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_import3); var _import4 = _dereq_('./text-track-enums'); var TextTrackEnum = _interopRequireWildcard(_import4); var _log = _dereq_('../utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _EventEmitter = _dereq_('../event-emitter'); var _EventEmitter2 = _interopRequireWildcard(_EventEmitter); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _XHR = _dereq_('../xhr.js'); var _XHR2 = _interopRequireWildcard(_XHR); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack * * interface TextTrack : EventTarget { * readonly attribute TextTrackKind kind; * readonly attribute DOMString label; * readonly attribute DOMString language; * * readonly attribute DOMString id; * readonly attribute DOMString inBandMetadataTrackDispatchType; * * attribute TextTrackMode mode; * * readonly attribute TextTrackCueList? cues; * readonly attribute TextTrackCueList? activeCues; * * void addCue(TextTrackCue cue); * void removeCue(TextTrackCue cue); * * attribute EventHandler oncuechange; * }; */ var TextTrack = (function (_TextTrack) { function TextTrack() { return _TextTrack.apply(this, arguments); } TextTrack.toString = function () { return _TextTrack.toString(); }; return TextTrack; })(function () { var options = arguments[0] === undefined ? {} : arguments[0]; if (!options.tech) { throw new Error('A tech was not provided.'); } var tt = this; if (browser.IS_IE8) { tt = _document2['default'].createElement('custom'); for (var prop in TextTrack.prototype) { tt[prop] = TextTrack.prototype[prop]; } } tt.tech_ = options.tech; var mode = TextTrackEnum.TextTrackMode[options.mode] || 'disabled'; var kind = TextTrackEnum.TextTrackKind[options.kind] || 'subtitles'; var label = options.label || ''; var language = options.language || options.srclang || ''; var id = options.id || 'vjs_text_track_' + Guid.newGUID(); if (kind === 'metadata' || kind === 'chapters') { mode = 'hidden'; } tt.cues_ = []; tt.activeCues_ = []; var cues = new _TextTrackCueList2['default'](tt.cues_); var activeCues = new _TextTrackCueList2['default'](tt.activeCues_); var changed = false; var timeupdateHandler = Fn.bind(tt, function () { this.activeCues; if (changed) { this.trigger('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.tech_.on('timeupdate', timeupdateHandler); } Object.defineProperty(tt, 'kind', { get: function get() { return kind; }, set: Function.prototype }); Object.defineProperty(tt, 'label', { get: function get() { return label; }, set: Function.prototype }); Object.defineProperty(tt, 'language', { get: function get() { return language; }, set: Function.prototype }); Object.defineProperty(tt, 'id', { get: function get() { return id; }, set: Function.prototype }); Object.defineProperty(tt, 'mode', { get: function get() { return mode; }, set: function set(newMode) { if (!TextTrackEnum.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.tech_.on('timeupdate', timeupdateHandler); } this.trigger('modechange'); } }); Object.defineProperty(tt, 'cues', { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: Function.prototype }); Object.defineProperty(tt, 'activeCues', { get: function get() { if (!this.loaded_) { return null; } if (this.cues.length === 0) { return activeCues; // nothing to do } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this.cues.length; i < l; i++) { var cue = this.cues[i]; if (cue.startTime <= ct && cue.endTime >= ct) { active.push(cue); } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var i = 0; i < active.length; i++) { if (indexOf.call(this.activeCues_, active[i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: Function.prototype }); if (options.src) { loadTrack(options.src, tt); } else { tt.loaded_ = true; } if (browser.IS_IE8) { return tt; } }); TextTrack.prototype = Object.create(_EventEmitter2['default'].prototype); TextTrack.prototype.constructor = TextTrack; /* * cuechange - One or more cues in the track have become active or stopped being active. */ TextTrack.prototype.allowedEvents_ = { cuechange: 'cuechange' }; TextTrack.prototype.addCue = function (cue) { var tracks = this.tech_.textTracks(); if (tracks) { for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this.cues.setCues_(this.cues_); }; TextTrack.prototype.removeCue = function (removeCue) { var removed = false; for (var i = 0, l = this.cues_.length; i < l; i++) { var cue = this.cues_[i]; if (cue === removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; /* * Downloading stuff happens below this point */ var parseCues = (function (_parseCues) { function parseCues(_x, _x2) { return _parseCues.apply(this, arguments); } parseCues.toString = function () { return _parseCues.toString(); }; return parseCues; })(function (srcContent, track) { if (typeof _window2['default'].WebVTT !== 'function') { //try again a bit later return _window2['default'].setTimeout(function () { parseCues(srcContent, track); }, 25); } var parser = new _window2['default'].WebVTT.Parser(_window2['default'], _window2['default'].vttjs, _window2['default'].WebVTT.StringDecoder()); parser.oncue = function (cue) { track.addCue(cue); }; parser.onparsingerror = function (error) { _log2['default'].error(error); }; parser.parse(srcContent); parser.flush(); }); var loadTrack = function loadTrack(src, track) { _XHR2['default'](src, Fn.bind(this, function (err, response, responseBody) { if (err) { return _log2['default'].error(err); } track.loaded_ = true; parseCues(responseBody, track); })); }; var indexOf = function indexOf(searchElement, fromIndex) { if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; exports['default'] = TextTrack; module.exports = exports['default']; },{"../event-emitter":83,"../utils/browser.js":108,"../utils/fn.js":112,"../utils/guid.js":114,"../utils/log.js":115,"../xhr.js":122,"./text-track-cue-list":102,"./text-track-enums":104,"global/document":1,"global/window":2}],108:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file browser.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var USER_AGENT = _window2['default'].navigator.userAgent; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPHONE = /iPhone/i.test(USER_AGENT); exports.IS_IPHONE = IS_IPHONE; var IS_IPAD = /iPad/i.test(USER_AGENT); exports.IS_IPAD = IS_IPAD; var IS_IPOD = /iPod/i.test(USER_AGENT); exports.IS_IPOD = IS_IPOD; var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; exports.IS_IOS = IS_IOS; var IOS_VERSION = (function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); exports.IOS_VERSION = IOS_VERSION; var IS_ANDROID = /Android/i.test(USER_AGENT); exports.IS_ANDROID = IS_ANDROID; var ANDROID_VERSION = (function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); exports.ANDROID_VERSION = ANDROID_VERSION; // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; exports.IS_OLD_ANDROID = IS_OLD_ANDROID; var IS_FIREFOX = /Firefox/i.test(USER_AGENT); exports.IS_FIREFOX = IS_FIREFOX; var IS_CHROME = /Chrome/i.test(USER_AGENT); exports.IS_CHROME = IS_CHROME; var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); exports.IS_IE8 = IS_IE8; var TOUCH_ENABLED = !!('ontouchstart' in _window2['default'] || _window2['default'].DocumentTouch && _document2['default'] instanceof _window2['default'].DocumentTouch); exports.TOUCH_ENABLED = TOUCH_ENABLED; var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _document2['default'].createElement('video').style); exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED; },{"global/document":1,"global/window":2}],109:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * Compute how much your video has been buffered * * @param {Object} Buffered object * @param {Number} Total duration * @return {Number} Percent buffered of the total duration * @private * @function bufferedPercent */ exports.bufferedPercent = bufferedPercent; /** * @file buffer.js */ var _createTimeRange = _dereq_('./time-ranges.js'); function bufferedPercent(buffered, duration) { var bufferedDuration = 0, start, end; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = _createTimeRange.createTimeRange(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } },{"./time-ranges.js":118}],110:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * * @param {String} id Element ID * @return {Element} Element with supplied ID * @function getEl */ exports.getEl = getEl; /** * Creates an element and applies properties. * * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @function createEl */ exports.createEl = createEl; /** * Insert an element as the first child node of another * * @param {Element} child Element to insert * @param {Element} parent Element to insert child into * @private * @function insertElFirst */ exports.insertElFirst = insertElFirst; /** * Returns the cache object where data for an element is stored * * @param {Element} el Element to store data for. * @return {Object} * @function getElData */ exports.getElData = getElData; /** * Returns whether or not an element has cached data * * @param {Element} el A dom element * @return {Boolean} * @private * @function hasElData */ exports.hasElData = hasElData; /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el Remove data for an element * @private * @function removeElData */ exports.removeElData = removeElData; /** * Check if an element has a CSS class * * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @function hasElClass */ exports.hasElClass = hasElClass; /** * Add a CSS class name to an element * * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @function addElClass */ exports.addElClass = addElClass; /** * Remove a CSS class name from an element * * @param {Element} element Element to remove from class name * @param {String} classToRemove Classname to remove * @function removeElClass */ exports.removeElClass = removeElClass; /** * Apply attributes to an HTML element. * * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private * @function setElAttributes */ exports.setElAttributes = setElAttributes; /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private * @function getElAttributes */ exports.getElAttributes = getElAttributes; /** * Attempt to block the ability to select text while dragging controls * * @return {Boolean} * @method blockTextSelection */ exports.blockTextSelection = blockTextSelection; /** * Turn off text selection blocking * * @return {Boolean} * @method unblockTextSelection */ exports.unblockTextSelection = unblockTextSelection; /** * Offset Left * getBoundingClientRect technique from * John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el Element from which to get offset * @return {Object=} * @method findElPosition */ exports.findElPosition = findElPosition; /** * @file dom.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _import = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_import); var _roundFloat = _dereq_('./round-float.js'); var _roundFloat2 = _interopRequireWildcard(_roundFloat); function getEl(id) { if (id.indexOf('#') === 0) { id = id.slice(1); } return _document2['default'].getElementById(id); } function createEl() { var tagName = arguments[0] === undefined ? 'div' : arguments[0]; var properties = arguments[1] === undefined ? {} : arguments[1]; var el = _document2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // Not remembering why we were checking for dash // but using setAttribute means you have to use getAttribute // The check for dash checks for the aria- * attributes, like aria-label, aria-valuemin. // The additional check for "role" is because the default method for adding attributes does not // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. The W3C allows for aria- * attributes to be used in pre-HTML5 docs. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem. if (propName.indexOf('aria-') !== -1 || propName === 'role') { el.setAttribute(propName, val); } else { el[propName] = val; } }); return el; } function insertElFirst(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {String} * @constant * @private */ var elIdAttr = 'vdata' + new Date().getTime(); function getElData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } function hasElData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } function removeElData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } function hasElClass(element, classToCheck) { return (' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1; } function addElClass(element, classToAdd) { if (!hasElClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } } function removeElClass(element, classToRemove) { if (!hasElClass(element, classToRemove)) { return; } var classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (var i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i, 1); } } element.className = classNames.join(' '); } function setElAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } function getElAttributes(tag) { var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } function blockTextSelection() { _document2['default'].body.focus(); _document2['default'].onselectstart = function () { return false; }; } function unblockTextSelection() { _document2['default'].onselectstart = function () { return true; }; } function findElPosition(el) { var box = undefined; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _document2['default'].documentElement; var body = _document2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _window2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _window2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: _roundFloat2['default'](left), top: _roundFloat2['default'](top) }; } },{"./guid.js":114,"./round-float.js":117,"global/document":1,"global/window":2}],111:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ exports.on = on; /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ exports.off = off; /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ exports.trigger = trigger; /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ exports.one = one; /** * Fix a native event to have standard property values * * @param {Object} event Event object to fix * @return {Object} * @private * @method fixEvent */ exports.fixEvent = fixEvent; /** * @file events.js * * Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ var _import = _dereq_('./dom.js'); var Dom = _interopRequireWildcard(_import); var _import2 = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_import2); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = Dom.getElData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = Guid.newGUID(); data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) return; event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event, hash); } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!Dom.hasElData(elem)) { return; }var data = Dom.getElData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); }return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) { return; } // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = Dom.getElData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = (function (_func) { function func() { return _func.apply(this, arguments); } func.toString = function () { return _func.toString(); }; return func; })(function () { off(elem, type, func); fn.apply(this, arguments); }); // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || _window2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _document2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = _document2['default'].documentElement, body = _document2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; } } // Returns fixed-up instance return event; } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private * @method _cleanUpEvents */ function _cleanUpEvents(elem, type) { var data = Dom.getElData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { Dom.removeElData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private * @function _handleMultipleEvents */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { //Call the event method for each one of the types fn(elem, type, callback); }); } },{"./dom.js":110,"./guid.js":114,"global/document":1,"global/window":2}],112:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file fn.js */ var _newGUID = _dereq_('./guid.js'); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private * @method bind */ var bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = _newGUID.newGUID(); } // Create the new function that changes the context var ret = function ret() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = uid ? uid + '_' + fn.guid : fn.guid; return ret; }; exports.bind = bind; },{"./guid.js":114}],113:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file format-time.js * * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private * @function formatTime */ function formatTime(seconds) { var guide = arguments[1] === undefined ? seconds : arguments[1]; return (function () { var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; })(); } exports['default'] = formatTime; module.exports = exports['default']; },{}],114:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; /** * Get the next unique ID * * @return {String} * @function newGUID */ exports.newGUID = newGUID; /** * @file guid.js * * Unique ID for an element or function * @type {Number} * @private */ var _guid = 1; function newGUID() { return _guid++; } },{}],115:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file log.js */ var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); /** * Log plain debug messages */ var log = function log() { _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ log.history = []; /** * Log error messages */ log.error = function () { _logType('error', arguments); }; /** * Log warning messages */ log.warn = function () { _logType('warn', arguments); }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {Object} args The args to be passed to the log * @private * @method _logType */ function _logType(type, args) { // convert args to an array to get array functions var argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist var noop = function noop() {}; var console = _window2['default'].console || { log: noop, warn: noop, error: noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase() + ':'); } else { // default to log with no prefix type = 'log'; } // add to history log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } exports['default'] = log; module.exports = exports['default']; },{"global/window":2}],116:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * Merge two options objects, recursively merging **only* * plain object * properties. Previously `deepMerge`. * * @param {Object} object The destination object * @param {...Object} source One or more objects to merge into the first * @returns {Object} The updated first object * @function mergeOptions */ exports['default'] = mergeOptions; /** * @file merge-options.js */ var _merge = _dereq_('lodash-compat/object/merge'); var _merge2 = _interopRequireWildcard(_merge); function isPlain(obj) { return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; } function mergeOptions() { var object = arguments[0] === undefined ? {} : arguments[0]; // Allow for infinite additional object args to merge Array.prototype.slice.call(arguments, 1).forEach(function (source) { // Recursively merge only plain objects // All other values will be directly copied _merge2['default'](object, source, function (a, b) { // If we're not working with a plain object, copy the value as is if (!isPlain(b)) { return b; } // If the new value is a plain object but the first object value is not // we need to create a new object for the first object to merge with. // This makes it consistent with how merge() works by default // and also protects from later changes the to first object affecting // the second object's values. if (!isPlain(a)) { return mergeOptions({}, b); } }); }); return object; } module.exports = exports['default']; },{"lodash-compat/object/merge":40}],117:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; /** * @file round-float.js * * Should round off a number to a decimal place * * @param {Number} num Number to round * @param {Number} dec Number of decimal places to round to * @return {Number} Rounded number * @private * @method roundFloat */ var roundFloat = function roundFloat(num) { var dec = arguments[1] === undefined ? 0 : arguments[1]; return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); }; exports["default"] = roundFloat; module.exports = exports["default"]; },{}],118:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; /** * @file time-ranges.js * * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @private * @method createTimeRange */ exports.createTimeRange = createTimeRange; function createTimeRange(start, end) { if (start === undefined && end === undefined) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: 1, start: (function (_start) { function start() { return _start.apply(this, arguments); } start.toString = function () { return _start.toString(); }; return start; })(function () { return start; }), end: (function (_end) { function end() { return _end.apply(this, arguments); } end.toString = function () { return _end.toString(); }; return end; })(function () { return end; }) }; } },{}],119:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; /** * @file to-title-case.js * * Uppercase the first letter of a string * * @param {String} string String to be uppercased * @return {String} * @private * @method toTitleCase */ function toTitleCase(string) { return string.charAt(0).toUpperCase() + string.slice(1); } exports["default"] = toTitleCase; module.exports = exports["default"]; },{}],120:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file url.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ var parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = _document2['default'].createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div = undefined; if (addToBody) { div = _document2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); _document2['default'].body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { _document2['default'].body.removeChild(div); } return details; }; exports.parseUrl = parseUrl; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * * @param {String} url URL to make absolute * @return {String} Absolute URL * @private * @method getAbsoluteURL */ var getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = _document2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } return url; }; exports.getAbsoluteURL = getAbsoluteURL; /** * Returns the extension of the passed file name. It will return an empty string if you pass an invalid path * * @param {String} path The fileName path like '/path/to/file.mp4' * @returns {String} The extension in lower case or an empty string if no extension could be found. * @method getFileExtension */ var getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; exports.getFileExtension = getFileExtension; },{"global/document":1}],121:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file video.js */ var _document = _dereq_('global/document'); var _document2 = _interopRequireWildcard(_document); var _import = _dereq_('./setup'); var setup = _interopRequireWildcard(_import); var _Component = _dereq_('./component'); var _Component2 = _interopRequireWildcard(_Component); var _globalOptions = _dereq_('./global-options.js'); var _globalOptions2 = _interopRequireWildcard(_globalOptions); var _Player = _dereq_('./player'); var _Player2 = _interopRequireWildcard(_Player); var _plugin = _dereq_('./plugins.js'); var _plugin2 = _interopRequireWildcard(_plugin); var _mergeOptions = _dereq_('../../src/js/utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); var _import2 = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_import2); var _assign = _dereq_('object.assign'); var _assign2 = _interopRequireWildcard(_assign); var _createTimeRange = _dereq_('./utils/time-ranges.js'); var _log = _dereq_('./utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _xhr = _dereq_('./xhr.js'); var _xhr2 = _interopRequireWildcard(_xhr); var _import3 = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_import3); var _import4 = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_import4); var _extendsFn = _dereq_('./extends.js'); var _extendsFn2 = _interopRequireWildcard(_extendsFn); var _merge2 = _dereq_('lodash-compat/object/merge'); var _merge3 = _interopRequireWildcard(_merge2); // Include the built-in techs var _Html5 = _dereq_('./tech/html5.js'); var _Html52 = _interopRequireWildcard(_Html5); var _Flash = _dereq_('./tech/flash.js'); var _Flash2 = _interopRequireWildcard(_Flash); // HTML5 Element Shim for IE8 if (typeof HTMLVideoElement === 'undefined') { _document2['default'].createElement('video'); _document2['default'].createElement('audio'); _document2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * ```js * var myPlayer = videojs('my_video_id'); * ``` * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {Player} A player instance * @mixes videojs * @method videojs */ var videojs = function videojs(id, options, ready) { var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (_Player2['default'].players[id]) { // If options or ready funtion are passed, warn if (options) { _log2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { _Player2['default'].players[id].ready(ready); } return _Player2['default'].players[id]; // Otherwise get element for ID } else { tag = Dom.getEl(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag.player || new _Player2['default'](tag, options, ready); }; // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /* * Current software version (semver) * * @type {String} */ videojs.VERSION = '5.0.0-rc.31'; /** * Get the global options object * * @return {Object} The global options object * @mixes videojs * @method getGlobalOptions */ videojs.getGlobalOptions = function () { return _globalOptions2['default']; }; /** * Set options that will apply to every player * ```js * videojs.setGlobalOptions({ * autoplay: true * }); * // -> all players will autoplay by default * ``` * NOTE: This will do a deep merge with the new options, * not overwrite the entire global options object. * * @return {Object} The updated global options object * @mixes videojs * @method setGlobalOptions */ videojs.setGlobalOptions = function (newOptions) { return _mergeOptions2['default'](_globalOptions2['default'], newOptions); }; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} The created players * @mixes videojs * @method getPlayers */ videojs.getPlayers = function () { return _Player2['default'].players; }; /** * Get a component class object by name * ```js * var VjsButton = videojs.getComponent('Button'); * // Create a new instance of the component * var myButton = new VjsButton(myPlayer); * ``` * * @return {Component} Component identified by name * @mixes videojs * @method getComponent */ videojs.getComponent = _Component2['default'].getComponent; /** * Register a component so it can referred to by name * Used when adding to other * components, either through addChild * `component.addChild('myComponent')` * or through default children options * `{ children: ['myComponent'] }`. * ```js * // Get a component to subclass * var VjsButton = videojs.getComponent('Button'); * // Subclass the component (see 'extends' doc for more info) * var MySpecialButton = videojs.extends(VjsButton, {}); * // Register the new component * VjsButton.registerComponent('MySepcialButton', MySepcialButton); * // (optionally) add the new component as a default player child * myPlayer.addChild('MySepcialButton'); * ``` * NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {String} The class name of the component * @param {Component} The component class * @return {Component} The newly registered component * @mixes videojs * @method registerComponent */ videojs.registerComponent = _Component2['default'].registerComponent; /* * A suite of browser and device tests * * @type {Object} */ videojs.browser = browser; /** * Subclass an existing class * Mimics ES6 subclassing with the `extends` keyword * ```js * // Create a basic javascript 'class' * function MyClass(name){ * // Set a property at initialization * this.myName = name; * } * // Create an instance method * MyClass.prototype.sayMyName = function(){ * alert(this.myName); * }; * // Subclass the exisitng class and change the name * // when initializing * var MySubClass = videojs.extends(MyClass, { * constructor: function(name) { * // Call the super class constructor for the subclass * MyClass.call(this, name) * } * }); * // Create an instance of the new sub class * var myInstance = new MySubClass('John'); * myInstance.sayMyName(); // -> should alert "John" * ``` * * @param {Function} The Class to subclass * @param {Object} An object including instace methods for the new class * Optionally including a `constructor` function * @return {Function} The newly created subclass * @mixes videojs * @method extends */ videojs['extends'] = _extendsFn2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * ```js * var defaultOptions = { * foo: true, * bar: { * a: true, * b: [1,2,3] * } * }; * var newOptions = { * foo: false, * bar: { * b: [4,5,6] * } * }; * var result = videojs.mergeOptions(defaultOptions, newOptions); * // result.foo = false; * // result.bar.a = true; * // result.bar.b = [4,5,6]; * ``` * * @param {Object} The options object whose values will be overriden * @param {Object} The options object with values to override the first * @param {Object} Any number of additional options objects * * @return {Object} a new object with the merged values * @mixes videojs * @method mergeOptions */ videojs.mergeOptions = _mergeOptions2['default']; /** * Change the context (this) of a function * * videojs.bind(newContext, function(){ * this === newContext * }); * * NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function(){}.bind(newContext);` instead of this. * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} */ videojs.bind = Fn.bind; /** * Create a Video.js player plugin * Plugins are only initialized when options for the plugin are included * in the player options, or the plugin function on the player instance is * called. * **See the plugin guide in the docs for a more detailed example** * ```js * // Make a plugin that alerts when the player plays * videojs.plugin('myPlugin', function(myPluginOptions) { * myPluginOptions = myPluginOptions || {}; * * var player = this; * var alertText = myPluginOptions.text || 'Player is playing!' * * player.on('play', function(){ * alert(alertText); * }); * }); * // USAGE EXAMPLES * // EXAMPLE 1: New player with plugin options, call plugin immediately * var player1 = videojs('idOne', { * myPlugin: { * text: 'Custom text!' * } * }); * // Click play * // --> Should alert 'Custom text!' * // EXAMPLE 3: New player, initialize plugin later * var player3 = videojs('idThree'); * // Click play * // --> NO ALERT * // Click pause * // Initialize plugin using the plugin function on the player instance * player3.myPlugin({ * text: 'Plugin added later!' * }); * // Click play * // --> Should alert 'Plugin added later!' * ``` * * @param {String} The plugin name * @param {Function} The plugin function that will be called with options * @mixes videojs * @method plugin */ videojs.plugin = _plugin2['default']; /** * Adding languages so that they're available to all players. * ```js * videojs.addLanguage('es', { 'Hello': 'Hola' }); * ``` * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting language dictionary object * @mixes videojs * @method addLanguage */ videojs.addLanguage = function (code, data) { var _merge; code = ('' + code).toLowerCase(); return _merge3['default'](_globalOptions2['default'].languages, (_merge = {}, _merge[code] = data, _merge))[code]; }; /** * Log debug messages. * * @param {...Object} messages One or more messages to log */ videojs.log = _log2['default']; /** * Creates an emulated TimeRange object. * * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @method createTimeRange */ videojs.createTimeRange = _createTimeRange.createTimeRange; /** * Simple http request for retrieving external files (e.g. text tracks) * * ##### Example * * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * * * API is modeled after the Raynos/xhr. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @returns {Object} The request */ videojs.xhr = _xhr2['default']; // REMOVING: We probably should add this to the migration plugin // // Expose but deprecate the window[componentName] method for accessing components // Object.getOwnPropertyNames(Component.components).forEach(function(name){ // let component = Component.components[name]; // // // A deprecation warning as the constuctor // module.exports[name] = function(player, options, ready){ // log.warn('Using videojs.'+name+' to access the '+name+' component has been deprecated. Please use videojs.getComponent("componentName")'); // // return new Component(player, options, ready); // }; // // // Allow the prototype and class methods to be accessible still this way // // Though anything that attempts to override class methods will no longer work // assign(module.exports[name], component); // }); /* * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define.amd) { define('videojs', [], function () { return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module.exports = videojs; } exports['default'] = videojs; module.exports = exports['default']; },{"../../src/js/utils/merge-options.js":116,"./component":52,"./extends.js":84,"./global-options.js":86,"./player":92,"./plugins.js":93,"./setup":95,"./tech/flash.js":98,"./tech/html5.js":99,"./utils/browser.js":108,"./utils/dom.js":110,"./utils/fn.js":112,"./utils/log.js":115,"./utils/time-ranges.js":118,"./xhr.js":122,"global/document":1,"lodash-compat/object/merge":40,"object.assign":44}],122:[function(_dereq_,module,exports){ 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; /** * @file xhr.js */ var _import = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_import); var _log = _dereq_('./utils/log.js'); var _log2 = _interopRequireWildcard(_log); var _mergeOptions = _dereq_('./utils/merge-options.js'); var _mergeOptions2 = _interopRequireWildcard(_mergeOptions); var _window = _dereq_('global/window'); var _window2 = _interopRequireWildcard(_window); /* * Simple http request for retrieving external files (e.g. text tracks) * ##### Example * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * ///////////// * API is modeled after the Raynos/xhr, which we hope to use after * getting browserify implemented. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @return {Object} The request * @method xhr */ var xhr = function xhr(options, callback) { var abortTimeout = undefined; // If options is a string it's the url if (typeof options === 'string') { options = { uri: options }; } // Merge with default options options = _mergeOptions2['default']({ method: 'GET', timeout: 45 * 1000 }, options); callback = callback || function () {}; var XHR = _window2['default'].XMLHttpRequest; if (typeof XHR === 'undefined') { // Shim XMLHttpRequest for older IEs XHR = function () { try { return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new _window2['default'].ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } var request = new XHR(); // Store a reference to the url on the request instance request.uri = options.uri; var urlInfo = Url.parseUrl(options.uri); var winLoc = _window2['default'].location; var successHandler = function successHandler() { _window2['default'].clearTimeout(abortTimeout); callback(null, request, request.response || request.responseText); }; var errorHandler = function errorHandler(err) { _window2['default'].clearTimeout(abortTimeout); if (!err || typeof err === 'string') { err = new Error(err); } callback(err, request); }; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = urlInfo.protocol + urlInfo.host !== winLoc.protocol + winLoc.host; // XDomainRequest -- Use for IE if XMLHTTPRequest2 isn't available // 'withCredentials' is only available in XMLHTTPRequest2 // Also XDomainRequest has a lot of gotchas, so only use if cross domain if (crossOrigin && _window2['default'].XDomainRequest && !('withCredentials' in request)) { request = new _window2['default'].XDomainRequest(); request.onload = successHandler; request.onerror = errorHandler; // These blank handlers need to be set to fix ie9 // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ request.onprogress = function () {}; request.ontimeout = function () {}; // XMLHTTPRequest } else { (function () { var fileUrl = urlInfo.protocol === 'file:' || winLoc.protocol === 'file:'; request.onreadystatechange = function () { if (request.readyState === 4) { if (request.timedout) { return errorHandler('timeout'); } if (request.status === 200 || fileUrl && request.status === 0) { successHandler(); } else { errorHandler(); } } }; if (options.timeout) { abortTimeout = _window2['default'].setTimeout(function () { if (request.readyState !== 4) { request.timedout = true; request.abort(); } }, options.timeout); } })(); } // open the connection try { // Third arg is async, or ignored by XDomainRequest request.open(options.method || 'GET', options.uri, true); } catch (err) { return errorHandler(err); } // withCredentials only supported by XMLHttpRequest2 if (options.withCredentials) { request.withCredentials = true; } if (options.responseType) { request.responseType = options.responseType; } // send the request try { request.send(); } catch (err) { return errorHandler(err); } return request; }; exports['default'] = xhr; module.exports = exports['default']; },{"./utils/log.js":115,"./utils/merge-options.js":116,"./utils/url.js":120,"global/window":2}]},{},[121])(121) }); //# sourceMappingURL=video.js.map /* vtt.js - v0.12.1 (https://github.com/mozilla/vtt.js) built on 08-07-2015 */ (function(root) { var vttjs = root.vttjs = {}; var cueShim = vttjs.VTTCue; var regionShim = vttjs.VTTRegion; var oldVTTCue = root.VTTCue; var oldVTTRegion = root.VTTRegion; vttjs.shim = function() { vttjs.VTTCue = cueShim; vttjs.VTTRegion = regionShim; }; vttjs.restore = function() { vttjs.VTTCue = oldVTTCue; vttjs.VTTRegion = oldVTTRegion; }; }(this)); /** * Copyright 2013 vtt.js Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(root, vttjs) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = root.VTTCue || VTTCue; vttjs.VTTCue = VTTCue; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(root, vttjs) { var scrollSetting = { "": true, "up": true }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; vttjs.VTTRegion = VTTRegion; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F, 0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E, 0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678, 0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A, 0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C, 0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5, 0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE, 0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7, 0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0, 0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9, 0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2, 0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB, 0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D, 0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718, 0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721, 0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A, 0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750, 0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759, 0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762, 0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B, 0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774, 0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D, 0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786, 0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F, 0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798, 0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1, 0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3, 0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC, 0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5, 0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE, 0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7, 0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802, 0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B, 0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814, 0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834, 0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D, 0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847, 0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850, 0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E, 0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9, 0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22, 0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55, 0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67, 0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82, 0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B, 0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94, 0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D, 0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF, 0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8, 0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB, 0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED, 0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6, 0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF, 0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08, 0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11, 0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A, 0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23, 0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C, 0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35, 0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E, 0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47, 0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50, 0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59, 0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62, 0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B, 0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74, 0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D, 0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86, 0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F, 0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98, 0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1, 0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA, 0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3, 0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC, 0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5, 0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE, 0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7, 0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0, 0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9, 0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2, 0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB, 0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04, 0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D, 0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16, 0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F, 0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28, 0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31, 0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A, 0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55, 0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E, 0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67, 0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70, 0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79, 0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82, 0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B, 0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96, 0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F, 0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8, 0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1, 0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA, 0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3, 0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4, 0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C, 0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95, 0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB, 0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4, 0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF, 0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8, 0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803, 0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E, 0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816, 0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E, 0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826, 0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E, 0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837, 0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844, 0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C, 0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854, 0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905, 0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D, 0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921, 0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929, 0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931, 0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939, 0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986, 0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E, 0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996, 0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E, 0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13, 0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D, 0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25, 0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D, 0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51, 0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60, 0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68, 0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70, 0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78, 0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00, 0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08, 0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10, 0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18, 0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20, 0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28, 0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30, 0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42, 0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A, 0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52, 0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64, 0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C, 0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01, 0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09, 0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11, 0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19, 0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21, 0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29, 0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31, 0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39, 0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41, 0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00, 0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09, 0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11, 0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19, 0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E, 0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E, 0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A, 0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74, 0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E, 0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87, 0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90, 0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98, 0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6, 0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF, 0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7, 0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD]; function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); for (var j = 0; j < strongRTLChars.length; j++) { if (strongRTLChars[j] === charCode) { return "rtl"; } } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%") }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px") }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, vttjs, decoder) { if (!decoder) { decoder = vttjs; vttjs = {}; } if (!vttjs) { vttjs = {}; } this.window = window; this.vttjs = vttjs; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this, (this.vttjs || {})));
src/svg-icons/av/snooze.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSnooze = (props) => ( <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-3-9h3.63L9 15.2V17h6v-2h-3.63L15 10.8V9H9v2z"/> </SvgIcon> ); AvSnooze = pure(AvSnooze); AvSnooze.displayName = 'AvSnooze'; AvSnooze.muiName = 'SvgIcon'; export default AvSnooze;
src/components/Feedback/Feedback.js
aalluri-navaratan/react-starter-kit
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import styles from './Feedback.css'; import withStyles from '../../decorators/withStyles'; @withStyles(styles) class Feedback { render() { return ( <div className="Feedback"> <div className="Feedback-container"> <a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a> <span className="Feedback-spacer">|</span> <a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a> </div> </div> ); } } export default Feedback;
ajax/libs/vega/3.0.9/vega-core.js
jonobr1/cdnjs
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('d3-request'), require('d3-dsv'), require('d3-time-format'), require('d3-array'), require('d3-shape'), require('d3-path'), require('d3-scale'), require('d3-scale-chromatic'), require('d3-interpolate'), require('d3-time'), require('d3-format'), require('d3-geo'), require('d3-force'), require('d3-collection'), require('d3-hierarchy'), require('d3-voronoi'), require('d3-color')) : typeof define === 'function' && define.amd ? define(['exports', 'd3-request', 'd3-dsv', 'd3-time-format', 'd3-array', 'd3-shape', 'd3-path', 'd3-scale', 'd3-scale-chromatic', 'd3-interpolate', 'd3-time', 'd3-format', 'd3-geo', 'd3-force', 'd3-collection', 'd3-hierarchy', 'd3-voronoi', 'd3-color'], factory) : (factory((global.vega = global.vega || {}),global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3,global.d3)); }(this, (function (exports,d3Request,d3Dsv,d3TimeFormat,d3Array,d3Shape,d3Path,$,_,$$1,d3Time,d3Format,d3Geo,d3Force,d3Collection,d3Hierarchy,d3Voronoi,d3Color) { 'use strict'; var accessor = function(fn, fields, name) { fn.fields = fields || []; fn.fname = name; return fn; }; function accessorName(fn) { return fn == null ? null : fn.fname; } function accessorFields(fn) { return fn == null ? null : fn.fields; } var error$1 = function(message) { throw Error(message); }; var splitAccessPath = function(p) { var path$$1 = [], q = null, b = 0, n = p.length, s = '', i, j, c; p = p + ''; function push() { path$$1.push(s + p.substring(i, j)); s = ''; i = j + 1; } for (i=j=0; j<n; ++j) { c = p[j]; if (c === '\\') { s += p.substring(i, j); i = ++j; } else if (c === q) { push(); q = null; b = -1; } else if (q) { continue; } else if (i === b && c === '"') { i = j + 1; q = c; } else if (i === b && c === "'") { i = j + 1; q = c; } else if (c === '.' && !b) { if (j > i) { push(); } else { i = j + 1; } } else if (c === '[') { if (j > i) push(); b = i = j + 1; } else if (c === ']') { if (!b) error$1('Access path missing open bracket: ' + p); if (b > 0) push(); b = 0; i = j + 1; } } if (b) error$1('Access path missing closing bracket: ' + p); if (q) error$1('Access path missing closing quote: ' + p); if (j > i) { j++; push(); } return path$$1; }; var isArray = Array.isArray; var isObject = function(_$$1) { return _$$1 === Object(_$$1); }; var isString = function(_$$1) { return typeof _$$1 === 'string'; }; function $$2(x) { return isArray(x) ? '[' + x.map($$2) + ']' : isObject(x) || isString(x) ? // Output valid JSON and JS source strings. // See http://timelessrepo.com/json-isnt-a-javascript-subset JSON.stringify(x).replace('\u2028','\\u2028').replace('\u2029', '\\u2029') : x; } var field = function(field, name) { var path$$1 = splitAccessPath(field), code = 'return _[' + path$$1.map($$2).join('][') + '];'; return accessor( Function('_', code), [(field = path$$1.length===1 ? path$$1[0] : field)], name || field ); }; var empty = []; var id = field('id'); var identity = accessor(function(_$$1) { return _$$1; }, empty, 'identity'); var zero = accessor(function() { return 0; }, empty, 'zero'); var one = accessor(function() { return 1; }, empty, 'one'); var truthy = accessor(function() { return true; }, empty, 'true'); var falsy = accessor(function() { return false; }, empty, 'false'); function log(method, level, input) { var args = [level].concat([].slice.call(input)); console[method].apply(console, args); // eslint-disable-line no-console } var None = 0; var Error$1 = 1; var Warn = 2; var Info = 3; var Debug = 4; var logger = function(_$$1) { var level = _$$1 || None; return { level: function(_$$1) { if (arguments.length) { level = +_$$1; return this; } else { return level; } }, error: function() { if (level >= Error$1) log('error', 'ERROR', arguments); return this; }, warn: function() { if (level >= Warn) log('warn', 'WARN', arguments); return this; }, info: function() { if (level >= Info) log('log', 'INFO', arguments); return this; }, debug: function() { if (level >= Debug) log('log', 'DEBUG', arguments); return this; } } }; var peek = function(array) { return array[array.length - 1]; }; var toNumber = function(_$$1) { return _$$1 == null || _$$1 === '' ? null : +_$$1; }; function exp(sign) { return function(x) { return sign * Math.exp(x); }; } function log$1(sign) { return function(x) { return Math.log(sign * x); }; } function pow(exponent) { return function(x) { return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent); }; } function pan(domain, delta, lift, ground) { var d0 = lift(domain[0]), d1 = lift(peek(domain)), dd = (d1 - d0) * delta; return [ ground(d0 - dd), ground(d1 - dd) ]; } function panLinear(domain, delta) { return pan(domain, delta, toNumber, identity); } function panLog(domain, delta) { var sign = Math.sign(domain[0]); return pan(domain, delta, log$1(sign), exp(sign)); } function panPow(domain, delta, exponent) { return pan(domain, delta, pow(exponent), pow(1/exponent)); } function zoom(domain, anchor, scale, lift, ground) { var d0 = lift(domain[0]), d1 = lift(peek(domain)), da = anchor != null ? lift(anchor) : (d0 + d1) / 2; return [ ground(da + (d0 - da) * scale), ground(da + (d1 - da) * scale) ]; } function zoomLinear(domain, anchor, scale) { return zoom(domain, anchor, scale, toNumber, identity); } function zoomLog(domain, anchor, scale) { var sign = Math.sign(domain[0]); return zoom(domain, anchor, scale, log$1(sign), exp(sign)); } function zoomPow(domain, anchor, scale, exponent) { return zoom(domain, anchor, scale, pow(exponent), pow(1/exponent)); } var array = function(_$$1) { return _$$1 != null ? (isArray(_$$1) ? _$$1 : [_$$1]) : []; }; var isFunction = function(_$$1) { return typeof _$$1 === 'function'; }; var compare = function(fields, orders) { var idx = [], cmp = (fields = array(fields)).map(function(f, i) { if (f == null) { return null; } else { idx.push(i); return isFunction(f) ? f : splitAccessPath(f).map($$2).join(']['); } }), n = idx.length - 1, ord = array(orders), code = 'var u,v;return ', i, j, f, u, v, d, t, lt, gt; if (n < 0) return null; for (j=0; j<=n; ++j) { i = idx[j]; f = cmp[i]; if (isFunction(f)) { d = 'f' + i; u = '(u=this.' + d + '(a))'; v = '(v=this.' + d + '(b))'; (t = t || {})[d] = f; } else { u = '(u=a['+f+'])'; v = '(v=b['+f+'])'; } d = '((v=v instanceof Date?+v:v),(u=u instanceof Date?+u:u))'; if (ord[i] !== 'descending') { gt = 1; lt = -1; } else { gt = -1; lt = 1; } code += '(' + u+'<'+v+'||u==null)&&v!=null?' + lt + ':(u>v||v==null)&&u!=null?' + gt + ':'+d+'!==u&&v===v?' + lt + ':v!==v&&u===u?' + gt + (i < n ? ':' : ':0'); } f = Function('a', 'b', code + ';'); if (t) f = f.bind(t); fields = fields.reduce(function(map, field) { if (isFunction(field)) { (accessorFields(field) || []).forEach(function(_$$1) { map[_$$1] = 1; }); } else if (field != null) { map[field + ''] = 1; } return map; }, {}); return accessor(f, Object.keys(fields)); }; var constant = function(_$$1) { return isFunction(_$$1) ? _$$1 : function() { return _$$1; }; }; var debounce = function(delay, handler) { var tid, evt; function callback() { handler(evt); tid = evt = null; } return function(e) { evt = e; if (tid) clearTimeout(tid); tid = setTimeout(callback, delay); }; }; var extend = function(_$$1) { for (var x, k, i=1, len=arguments.length; i<len; ++i) { x = arguments[i]; for (k in x) { _$$1[k] = x[k]; } } return _$$1; }; var extentIndex = function(array, f) { var i = -1, n = array.length, a, b, c, u, v; if (f == null) { while (++i < n) { b = array[i]; if (b != null && b >= b) { a = c = b; break; } } u = v = i; while (++i < n) { b = array[i]; if (b != null) { if (a > b) { a = b; u = i; } if (c < b) { c = b; v = i; } } } } else { while (++i < n) { b = f(array[i], i, array); if (b != null && b >= b) { a = c = b; break; } } u = v = i; while (++i < n) { b = f(array[i], i, array); if (b != null) { if (a > b) { a = b; u = i; } if (c < b) { c = b; v = i; } } } } return [u, v]; }; var NULL = {}; var fastmap = function(input) { var obj = {}, map, test; function has(key) { return obj.hasOwnProperty(key) && obj[key] !== NULL; } map = { size: 0, empty: 0, object: obj, has: has, get: function(key) { return has(key) ? obj[key] : undefined; }, set: function(key, value) { if (!has(key)) { ++map.size; if (obj[key] === NULL) --map.empty; } obj[key] = value; return this; }, delete: function(key) { if (has(key)) { --map.size; ++map.empty; obj[key] = NULL; } return this; }, clear: function() { map.size = map.empty = 0; map.object = obj = {}; }, test: function(_$$1) { if (arguments.length) { test = _$$1; return map; } else { return test; } }, clean: function() { var next = {}, size = 0, key, value; for (key in obj) { value = obj[key]; if (value !== NULL && (!test || !test(value))) { next[key] = value; ++size; } } map.size = size; map.empty = 0; map.object = (obj = next); } }; if (input) Object.keys(input).forEach(function(key) { map.set(key, input[key]); }); return map; }; var inherits = function(child, parent) { var proto = (child.prototype = Object.create(parent.prototype)); proto.constructor = child; return proto; }; var isBoolean = function(_$$1) { return typeof _$$1 === 'boolean'; }; var isDate = function(_$$1) { return Object.prototype.toString.call(_$$1) === '[object Date]'; }; var isNumber = function(_$$1) { return typeof _$$1 === 'number'; }; var isRegExp = function(_$$1) { return Object.prototype.toString.call(_$$1) === '[object RegExp]'; }; var key = function(fields, flat) { if (fields) { fields = flat ? array(fields).map(function(f) { return f.replace(/\\(.)/g, '$1'); }) : array(fields); } var fn = !(fields && fields.length) ? function() { return ''; } : Function('_', 'return \'\'+' + fields.map(function(f) { return '_[' + (flat ? $$2(f) : splitAccessPath(f).map($$2).join('][') ) + ']'; }).join('+\'|\'+') + ';'); return accessor(fn, fields, 'key'); }; var merge = function(compare, array0, array1, output) { var n0 = array0.length, n1 = array1.length; if (!n1) return array0; if (!n0) return array1; var merged = output || new array0.constructor(n0 + n1), i0 = 0, i1 = 0, i = 0; for (; i0<n0 && i1<n1; ++i) { merged[i] = compare(array0[i0], array1[i1]) > 0 ? array1[i1++] : array0[i0++]; } for (; i0<n0; ++i0, ++i) { merged[i] = array0[i0]; } for (; i1<n1; ++i1, ++i) { merged[i] = array1[i1]; } return merged; }; var repeat = function(str, reps) { var s = ''; while (--reps >= 0) s += str; return s; }; var pad = function(str, length, padchar, align) { var c = padchar || ' ', s = str + '', n = length - s.length; return n <= 0 ? s : align === 'left' ? repeat(c, n) + s : align === 'center' ? repeat(c, ~~(n/2)) + s + repeat(c, Math.ceil(n/2)) : s + repeat(c, n); }; var toBoolean = function(_$$1) { return _$$1 == null || _$$1 === '' ? null : !_$$1 || _$$1 === 'false' || _$$1 === '0' ? false : !!_$$1; }; function defaultParser(_$$1) { return isNumber(_$$1) ? _$$1 : isDate(_$$1) ? _$$1 : Date.parse(_$$1); } var toDate = function(_$$1, parser) { parser = parser || defaultParser; return _$$1 == null || _$$1 === '' ? null : parser(_$$1); }; var toString = function(_$$1) { return _$$1 == null || _$$1 === '' ? null : _$$1 + ''; }; var toSet = function(_$$1) { for (var s={}, i=0, n=_$$1.length; i<n; ++i) s[_$$1[i]] = 1; return s; }; var truncate = function(str, length, align, ellipsis) { var e = ellipsis != null ? ellipsis : '\u2026', s = str + '', n = s.length, l = Math.max(0, length - e.length); return n <= length ? s : align === 'left' ? e + s.slice(n - l) : align === 'center' ? s.slice(0, Math.ceil(l/2)) + e + s.slice(n - ~~(l/2)) : s.slice(0, l) + e; }; var visitArray = function(array, filter, visitor) { if (array) { var i = 0, n = array.length, t; if (filter) { for (; i<n; ++i) { if (t = filter(array[i])) visitor(t, i, array); } } else { array.forEach(visitor); } } }; function UniqueList(idFunc) { var $$$1 = idFunc || identity, list = [], ids = {}; list.add = function(_$$1) { var id$$1 = $$$1(_$$1); if (!ids[id$$1]) { ids[id$$1] = 1; list.push(_$$1); } return list; }; list.remove = function(_$$1) { var id$$1 = $$$1(_$$1), idx; if (ids[id$$1]) { ids[id$$1] = 0; if ((idx = list.indexOf(_$$1)) >= 0) { list.splice(idx, 1); } } return list; }; return list; } var TUPLE_ID_KEY = Symbol('vega_id'); var TUPLE_ID = 1; /** * Resets the internal tuple id counter to one. */ /** * Checks if an input value is a registered tuple. * @param {*} t - The value to check. * @return {boolean} True if the input is a tuple, false otherwise. */ function isTuple(t) { return !!(t && tupleid(t)); } /** * Returns the id of a tuple. * @param {object} t - The input tuple. * @return {*} the tuple id. */ function tupleid(t) { return t[TUPLE_ID_KEY]; } /** * Sets the id of a tuple. * @param {object} t - The input tuple. * @param {*} id - The id value to set. * @return {object} the input tuple. */ function setid(t, id) { t[TUPLE_ID_KEY] = id; return t; } /** * Ingest an object or value as a data tuple. * If the input value is an object, an id field will be added to it. For * efficiency, the input object is modified directly. A copy is not made. * If the input value is a literal, it will be wrapped in a new object * instance, with the value accessible as the 'data' property. * @param datum - The value to ingest. * @return {object} The ingested data tuple. */ function ingest(datum) { var t = (datum === Object(datum)) ? datum : {data: datum}; return tupleid(t) ? t : setid(t, TUPLE_ID++); } /** * Given a source tuple, return a derived copy. * @param {object} t - The source tuple. * @return {object} The derived tuple. */ function derive(t) { return rederive(t, ingest({})); } /** * Rederive a derived tuple by copying values from the source tuple. * @param {object} t - The source tuple. * @param {object} d - The derived tuple. * @return {object} The derived tuple. */ function rederive(t, d) { for (var k in t) d[k] = t[k]; return d; } /** * Replace an existing tuple with a new tuple. * @param {object} t - The existing data tuple. * @param {object} d - The new tuple that replaces the old. * @return {object} The new tuple. */ function replace(t, d) { return setid(d, tupleid(t)); } function isChangeSet(v) { return v && v.constructor === changeset; } function changeset() { var add = [], // insert tuples rem = [], // remove tuples mod = [], // modify tuples remp = [], // remove by predicate modp = [], // modify by predicate reflow = false; return { constructor: changeset, insert: function(t) { var d = array(t), i = 0, n = d.length; for (; i<n; ++i) add.push(d[i]); return this; }, remove: function(t) { var a = isFunction(t) ? remp : rem, d = array(t), i = 0, n = d.length; for (; i<n; ++i) a.push(d[i]); return this; }, modify: function(t, field$$1, value) { var m = {field: field$$1, value: constant(value)}; if (isFunction(t)) { m.filter = t; modp.push(m); } else { m.tuple = t; mod.push(m); } return this; }, encode: function(t, set) { if (isFunction(t)) modp.push({filter: t, field: set}); else mod.push({tuple: t, field: set}); return this; }, reflow: function() { reflow = true; return this; }, pulse: function(pulse, tuples) { var out, i, n, m, f, t, id$$1; // add for (i=0, n=add.length; i<n; ++i) { pulse.add.push(ingest(add[i])); } // remove for (out={}, i=0, n=rem.length; i<n; ++i) { t = rem[i]; out[tupleid(t)] = t; } for (i=0, n=remp.length; i<n; ++i) { f = remp[i]; tuples.forEach(function(t) { if (f(t)) out[tupleid(t)] = t; }); } for (id$$1 in out) pulse.rem.push(out[id$$1]); // modify function modify(t, f, v) { if (v) t[f] = v(t); else pulse.encode = f; if (!reflow) out[tupleid(t)] = t; } for (out={}, i=0, n=mod.length; i<n; ++i) { m = mod[i]; modify(m.tuple, m.field, m.value); pulse.modifies(m.field); } for (i=0, n=modp.length; i<n; ++i) { m = modp[i]; f = m.filter; tuples.forEach(function(t) { if (f(t)) modify(t, m.field, m.value); }); pulse.modifies(m.field); } // reflow? if (reflow) { pulse.mod = rem.length || remp.length ? tuples.filter(function(t) { return out.hasOwnProperty(tupleid(t)); }) : tuples.slice(); } else { for (id$$1 in out) pulse.mod.push(out[id$$1]); } return pulse; } }; } var CACHE = '_:mod:_'; /** * Hash that tracks modifications to assigned values. * Callers *must* use the set method to update values. */ function Parameters() { Object.defineProperty(this, CACHE, {writable:true, value: {}}); } var prototype$2 = Parameters.prototype; /** * Set a parameter value. If the parameter value changes, the parameter * will be recorded as modified. * @param {string} name - The parameter name. * @param {number} index - The index into an array-value parameter. Ignored if * the argument is undefined, null or less than zero. * @param {*} value - The parameter value to set. * @param {boolean} [force=false] - If true, records the parameter as modified * even if the value is unchanged. * @return {Parameters} - This parameter object. */ prototype$2.set = function(name, index, value, force) { var o = this, v = o[name], mod = o[CACHE]; if (index != null && index >= 0) { if (v[index] !== value || force) { v[index] = value; mod[index + ':' + name] = -1; mod[name] = -1; } } else if (v !== value || force) { o[name] = value; mod[name] = isArray(value) ? 1 + value.length : -1; } return o; }; /** * Tests if one or more parameters has been modified. If invoked with no * arguments, returns true if any parameter value has changed. If the first * argument is array, returns trues if any parameter name in the array has * changed. Otherwise, tests if the given name and optional array index has * changed. * @param {string} name - The parameter name to test. * @param {number} [index=undefined] - The parameter array index to test. * @return {boolean} - Returns true if a queried parameter was modified. */ prototype$2.modified = function(name, index) { var mod = this[CACHE], k; if (!arguments.length) { for (k in mod) { if (mod[k]) return true; } return false; } else if (isArray(name)) { for (k=0; k<name.length; ++k) { if (mod[name[k]]) return true; } return false; } return (index != null && index >= 0) ? (index + 1 < mod[name] || !!mod[index + ':' + name]) : !!mod[name]; }; /** * Clears the modification records. After calling this method, * all parameters are considered unmodified. */ prototype$2.clear = function() { this[CACHE] = {}; return this; }; var OP_ID = 0; var PULSE = 'pulse'; var NO_PARAMS = new Parameters(); // Boolean Flags var SKIP = 1; var MODIFIED = 2; /** * An Operator is a processing node in a dataflow graph. * Each operator stores a value and an optional value update function. * Operators can accept a hash of named parameters. Parameter values can * either be direct (JavaScript literals, arrays, objects) or indirect * (other operators whose values will be pulled dynamically). Operators * included as parameters will have this operator added as a dependency. * @constructor * @param {*} [init] - The initial value for this operator. * @param {function(object, Pulse)} [update] - An update function. Upon * evaluation of this operator, the update function will be invoked and the * return value will be used as the new value of this operator. * @param {object} [params] - The parameters for this operator. * @param {boolean} [react=true] - Flag indicating if this operator should * listen for changes to upstream operators included as parameters. * @see parameters */ function Operator(init, update, params, react) { this.id = ++OP_ID; this.value = init; this.stamp = -1; this.rank = -1; this.qrank = -1; this.flags = 0; if (update) { this._update = update; } if (params) this.parameters(params, react); } var prototype$1 = Operator.prototype; /** * Returns a list of target operators dependent on this operator. * If this list does not exist, it is created and then returned. * @return {UniqueList} */ prototype$1.targets = function() { return this._targets || (this._targets = UniqueList(id)); }; /** * Sets the value of this operator. * @param {*} value - the value to set. * @return {Number} Returns 1 if the operator value has changed * according to strict equality, returns 0 otherwise. */ prototype$1.set = function(value) { if (this.value !== value) { this.value = value; return 1; } else { return 0; } }; function flag(bit) { return function(state) { var f = this.flags; if (arguments.length === 0) return !!(f & bit); this.flags = state ? (f | bit) : (f & ~bit); return this; }; } /** * Indicates that operator evaluation should be skipped on the next pulse. * This operator will still propagate incoming pulses, but its update function * will not be invoked. The skip flag is reset after every pulse, so calling * this method will affect processing of the next pulse only. */ prototype$1.skip = flag(SKIP); /** * Indicates that this operator's value has been modified on its most recent * pulse. Normally modification is checked via strict equality; however, in * some cases it is more efficient to update the internal state of an object. * In those cases, the modified flag can be used to trigger propagation. Once * set, the modification flag persists across pulses until unset. The flag can * be used with the last timestamp to test if a modification is recent. */ prototype$1.modified = flag(MODIFIED); /** * Sets the parameters for this operator. The parameter values are analyzed for * operator instances. If found, this operator will be added as a dependency * of the parameterizing operator. Operator values are dynamically marshalled * from each operator parameter prior to evaluation. If a parameter value is * an array, the array will also be searched for Operator instances. However, * the search does not recurse into sub-arrays or object properties. * @param {object} params - A hash of operator parameters. * @param {boolean} [react=true] - A flag indicating if this operator should * automatically update (react) when parameter values change. In other words, * this flag determines if the operator registers itself as a listener on * any upstream operators included in the parameters. * @return {Operator[]} - An array of upstream dependencies. */ prototype$1.parameters = function(params, react) { react = react !== false; var self = this, argval = (self._argval = self._argval || new Parameters()), argops = (self._argops = self._argops || []), deps = [], name, value, n, i; function add(name, index, value) { if (value instanceof Operator) { if (value !== self) { if (react) value.targets().add(self); deps.push(value); } argops.push({op:value, name:name, index:index}); } else { argval.set(name, index, value); } } for (name in params) { value = params[name]; if (name === PULSE) { array(value).forEach(function(op) { if (!(op instanceof Operator)) { error$1('Pulse parameters must be operator instances.'); } else if (op !== self) { op.targets().add(self); deps.push(op); } }); self.source = value; } else if (isArray(value)) { argval.set(name, -1, Array(n = value.length)); for (i=0; i<n; ++i) add(name, i, value[i]); } else { add(name, -1, value); } } this.marshall().clear(); // initialize values return deps; }; /** * Internal method for marshalling parameter values. * Visits each operator dependency to pull the latest value. * @return {Parameters} A Parameters object to pass to the update function. */ prototype$1.marshall = function(stamp) { var argval = this._argval || NO_PARAMS, argops = this._argops, item, i, n, op, mod; if (argops && (n = argops.length)) { for (i=0; i<n; ++i) { item = argops[i]; op = item.op; mod = op.modified() && op.stamp === stamp; argval.set(item.name, item.index, op.value, mod); } } return argval; }; /** * Delegate method to perform operator processing. * Subclasses can override this method to perform custom processing. * By default, it marshalls parameters and calls the update function * if that function is defined. If the update function does not * change the operator value then StopPropagation is returned. * If no update function is defined, this method does nothing. * @param {Pulse} pulse - the current dataflow pulse. * @return The output pulse or StopPropagation. A falsy return value * (including undefined) will let the input pulse pass through. */ prototype$1.evaluate = function(pulse) { if (this._update) { var params = this.marshall(pulse.stamp), v = this._update(params, pulse); params.clear(); if (v !== this.value) { this.value = v; } else if (!this.modified()) { return pulse.StopPropagation; } } }; /** * Run this operator for the current pulse. If this operator has already * been run at (or after) the pulse timestamp, returns StopPropagation. * Internally, this method calls {@link evaluate} to perform processing. * If {@link evaluate} returns a falsy value, the input pulse is returned. * This method should NOT be overridden, instead overrride {@link evaluate}. * @param {Pulse} pulse - the current dataflow pulse. * @return the output pulse for this operator (or StopPropagation) */ prototype$1.run = function(pulse) { if (pulse.stamp <= this.stamp) return pulse.StopPropagation; var rv; if (this.skip()) { this.skip(false); rv = 0; } else { rv = this.evaluate(pulse); } this.stamp = pulse.stamp; this.pulse = rv; return rv || pulse; }; /** * Add an operator to the dataflow graph. This function accepts a * variety of input argument types. The basic signature supports an * initial value, update function and parameters. If the first parameter * is an Operator instance, it will be added directly. If it is a * constructor for an Operator subclass, a new instance will be instantiated. * Otherwise, if the first parameter is a function instance, it will be used * as the update function and a null initial value is assumed. * @param {*} init - One of: the operator to add, the initial value of * the operator, an operator class to instantiate, or an update function. * @param {function} [update] - The operator update function. * @param {object} [params] - The operator parameters. * @param {boolean} [react=true] - Flag indicating if this operator should * listen for changes to upstream operators included as parameters. * @return {Operator} - The added operator. */ var add = function(init, update, params, react) { var shift = 1, op; if (init instanceof Operator) { op = init; } else if (init && init.prototype instanceof Operator) { op = new init(); } else if (isFunction(init)) { op = new Operator(null, init); } else { shift = 0; op = new Operator(init, update); } this.rank(op); if (shift) { react = params; params = update; } if (params) this.connect(op, op.parameters(params, react)); this.touch(op); return op; }; /** * Connect a target operator as a dependent of source operators. * If necessary, this method will rerank the target operator and its * dependents to ensure propagation proceeds in a topologically sorted order. * @param {Operator} target - The target operator. * @param {Array<Operator>} - The source operators that should propagate * to the target operator. */ var connect = function(target, sources) { var targetRank = target.rank, i, n; for (i=0, n=sources.length; i<n; ++i) { if (targetRank < sources[i].rank) { this.rerank(target); return; } } }; var STREAM_ID = 0; /** * Models an event stream. * @constructor * @param {function(Object, number): boolean} [filter] - Filter predicate. * Events pass through when truthy, events are suppressed when falsy. * @param {function(Object): *} [apply] - Applied to input events to produce * new event values. * @param {function(Object)} [receive] - Event callback function to invoke * upon receipt of a new event. Use to override standard event processing. */ function EventStream(filter, apply, receive) { this.id = ++STREAM_ID; this.value = null; if (receive) this.receive = receive; if (filter) this._filter = filter; if (apply) this._apply = apply; } /** * Creates a new event stream instance with the provided * (optional) filter, apply and receive functions. * @param {function(Object, number): boolean} [filter] - Filter predicate. * Events pass through when truthy, events are suppressed when falsy. * @param {function(Object): *} [apply] - Applied to input events to produce * new event values. * @see EventStream */ function stream(filter, apply, receive) { return new EventStream(filter, apply, receive); } var prototype$3 = EventStream.prototype; prototype$3._filter = truthy; prototype$3._apply = identity; prototype$3.targets = function() { return this._targets || (this._targets = UniqueList(id)); }; prototype$3.consume = function(_$$1) { if (!arguments.length) return !!this._consume; this._consume = !!_$$1; return this; }; prototype$3.receive = function(evt) { if (this._filter(evt)) { var val = (this.value = this._apply(evt)), trg = this._targets, n = trg ? trg.length : 0, i = 0; for (; i<n; ++i) trg[i].receive(val); if (this._consume) { evt.preventDefault(); evt.stopPropagation(); } } }; prototype$3.filter = function(filter) { var s = stream(filter); this.targets().add(s); return s; }; prototype$3.apply = function(apply) { var s = stream(null, apply); this.targets().add(s); return s; }; prototype$3.merge = function() { var s = stream(); this.targets().add(s); for (var i=0, n=arguments.length; i<n; ++i) { arguments[i].targets().add(s); } return s; }; prototype$3.throttle = function(pause) { var t = -1; return this.filter(function() { var now = Date.now(); if ((now - t) > pause) { t = now; return 1; } else { return 0; } }); }; prototype$3.debounce = function(delay) { var s = stream(); this.targets().add(stream(null, null, debounce(delay, function(e) { var df = e.dataflow; s.receive(e); if (df && df.run) df.run(); }) )); return s; }; prototype$3.between = function(a, b) { var active = false; a.targets().add(stream(null, null, function() { active = true; })); b.targets().add(stream(null, null, function() { active = false; })); return this.filter(function() { return active; }); }; /** * Create a new event stream from an event source. * @param {object} source - The event source to monitor. The input must * support the addEventListener method. * @param {string} type - The event type. * @param {function(object): boolean} [filter] - Event filter function. * @param {function(object): *} [apply] - Event application function. * If provided, this function will be invoked and the result will be * used as the downstream event value. * @return {EventStream} */ var events = function(source, type, filter, apply) { var df = this, s = stream(filter, apply), send = function(e) { e.dataflow = df; try { s.receive(e); } catch (error) { df.error(error); } finally { df.run(); } }, sources; if (typeof source === 'string' && typeof document !== 'undefined') { sources = document.querySelectorAll(source); } else { sources = array(source); } for (var i=0, n=sources.length; i<n; ++i) { sources[i].addEventListener(type, send); } return s; }; // Matches absolute URLs with optional protocol // https://... file://... //... var protocol_re = /^([A-Za-z]+:)?\/\//; // Special treatment in node.js for the file: protocol var fileProtocol = 'file://'; // Request options to check for d3-request var requestOptions = [ 'mimeType', 'responseType', 'user', 'password' ]; /** * Creates a new loader instance that provides methods for requesting files * from either the network or disk, and for sanitizing request URIs. * @param {object} [options] - Optional default loading options to use. * @return {object} - A new loader instance. */ var loader = function(options) { return { options: options || {}, sanitize: sanitize, load: load, file: file, http: http }; }; function marshall(loader, options) { return extend({}, loader.options, options); } /** * Load an external resource, typically either from the web or from the local * filesystem. This function uses {@link sanitize} to first sanitize the uri, * then calls either {@link http} (for web requests) or {@link file} (for * filesystem loading). * @param {string} uri - The resource indicator (e.g., URL or filename). * @param {object} [options] - Optional loading options. These options will * override any existing default options. * @return {Promise} - A promise that resolves to the loaded content. */ function load(uri, options) { var loader = this; return loader.sanitize(uri, options) .then(function(opt) { var url = opt.href; return opt.localFile ? loader.file(url) : loader.http(url, options); }); } /** * URI sanitizer function. * @param {string} uri - The uri (url or filename) to sanity check. * @param {object} options - An options hash. * @return {Promise} - A promise that resolves to an object containing * sanitized uri data, or rejects it the input uri is deemed invalid. * The properties of the resolved object are assumed to be * valid attributes for an HTML 'a' tag. The sanitized uri *must* be * provided by the 'href' property of the returned object. */ function sanitize(uri, options) { options = marshall(this, options); return new Promise(function(accept, reject) { var result = {href: null}, isFile, hasProtocol, loadFile, base; if (uri == null || typeof uri !== 'string') { reject('Sanitize failure, invalid URI: ' + $$2(uri)); return; } hasProtocol = protocol_re.test(uri); // if relative url (no protocol/host), prepend baseURL if ((base = options.baseURL) && !hasProtocol) { // Ensure that there is a slash between the baseURL (e.g. hostname) and url if (!startsWith(uri, '/') && base[base.length-1] !== '/') { uri = '/' + uri; } uri = base + uri; } // should we load from file system? loadFile = (isFile = startsWith(uri, fileProtocol)) || options.mode === 'file' || options.mode !== 'http' && !hasProtocol && fs(); if (isFile) { // strip file protocol uri = uri.slice(fileProtocol.length); } else if (startsWith(uri, '//')) { if (options.defaultProtocol === 'file') { // if is file, strip protocol and set loadFile flag uri = uri.slice(2); loadFile = true; } else { // if relative protocol (starts with '//'), prepend default protocol uri = (options.defaultProtocol || 'http') + ':' + uri; } } // set non-enumerable mode flag to indicate local file load Object.defineProperty(result, 'localFile', {value: !!loadFile}); // set uri and return result.href = uri; accept(result); }); } /** * HTTP request loader. * @param {string} url - The url to request. * @param {object} options - An options hash. * @return {Promise} - A promise that resolves to the file contents. */ function http(url, options) { options = marshall(this, options); return new Promise(function(accept, reject) { var req = d3Request.request(url), name; for (name in options.headers) { req.header(name, options.headers[name]); } requestOptions.forEach(function(name) { if (options[name]) req[name](options[name]); }); req.on('error', function(error) { reject(error || 'Error loading URL: ' + url); }) .on('load', function(result) { var text = result && result.responseText; (!result || result.status === 0) ? reject(text || 'Error') : accept(text); }) .get(); }); } /** * File system loader. * @param {string} filename - The file system path to load. * @return {Promise} - A promise that resolves to the file contents. */ function file(filename) { return new Promise(function(accept, reject) { var f = fs(); f ? f.readFile(filename, function(error, data) { if (error) reject(error); else accept(data); }) : reject('No file system access for ' + filename); }); } function fs() { var fs = typeof require === 'function' && require('fs'); return fs && isFunction(fs.readFile) ? fs : null; } function startsWith(string, query) { return string == null ? false : string.lastIndexOf(query, 0) === 0; } var typeParsers = { boolean: toBoolean, integer: toNumber, number: toNumber, date: toDate, string: toString, unknown: identity }; var typeTests = [ isBoolean$1, isInteger, isNumber$1, isDate$1 ]; var typeList = [ 'boolean', 'integer', 'number', 'date' ]; function inferType(values, field$$1) { if (!values || !values.length) return 'unknown'; var tests = typeTests.slice(), value, i, n, j; for (i=0, n=values.length; i<n; ++i) { value = field$$1 ? values[i][field$$1] : values[i]; for (j=0; j<tests.length; ++j) { if (isValid(value) && !tests[j](value)) { tests.splice(j, 1); --j; } } if (tests.length === 0) return 'string'; } return typeList[typeTests.indexOf(tests[0])]; } function inferTypes(data, fields) { return fields.reduce(function(types, field$$1) { types[field$$1] = inferType(data, field$$1); return types; }, {}); } // -- Type Checks ---- function isValid(_$$1) { return _$$1 != null && _$$1 === _$$1; } function isBoolean$1(_$$1) { return _$$1 === 'true' || _$$1 === 'false' || _$$1 === true || _$$1 === false; } function isDate$1(_$$1) { return !isNaN(Date.parse(_$$1)); } function isNumber$1(_$$1) { return !isNaN(+_$$1) && !(_$$1 instanceof Date); } function isInteger(_$$1) { return isNumber$1(_$$1) && (_$$1=+_$$1) === ~~_$$1; } function delimitedFormat(delimiter) { return function(data, format$$1) { var delim = {delimiter: delimiter}; return dsv(data, format$$1 ? extend(format$$1, delim) : delim); }; } function dsv(data, format$$1) { if (format$$1.header) { data = format$$1.header .map($$2) .join(format$$1.delimiter) + '\n' + data; } return d3Dsv.dsvFormat(format$$1.delimiter).parse(data+''); } function isBuffer(_$$1) { return (typeof Buffer === 'function' && isFunction(Buffer.isBuffer)) ? Buffer.isBuffer(_$$1) : false; } var json = function(data, format$$1) { var prop = (format$$1 && format$$1.property) ? field(format$$1.property) : identity; return isObject(data) && !isBuffer(data) ? parseJSON(prop(data)) : prop(JSON.parse(data)); }; function parseJSON(data, format$$1) { return (format$$1 && format$$1.copy) ? JSON.parse(JSON.stringify(data)) : data; } var identity$1 = function(x) { return x; }; var transform = function(transform) { if (transform == null) return identity$1; var x0, y0, kx = transform.scale[0], ky = transform.scale[1], dx = transform.translate[0], dy = transform.translate[1]; return function(input, i) { if (!i) x0 = y0 = 0; var j = 2, n = input.length, output = new Array(n); output[0] = (x0 += input[0]) * kx + dx; output[1] = (y0 += input[1]) * ky + dy; while (j < n) output[j] = input[j], ++j; return output; }; }; var reverse = function(array, n) { var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; }; var feature = function(topology, o) { return o.type === "GeometryCollection" ? {type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); })} : feature$1(topology, o); }; function feature$1(topology, o) { var id = o.id, bbox = o.bbox, properties = o.properties == null ? {} : o.properties, geometry = object(topology, o); return id == null && bbox == null ? {type: "Feature", properties: properties, geometry: geometry} : bbox == null ? {type: "Feature", id: id, properties: properties, geometry: geometry} : {type: "Feature", id: id, bbox: bbox, properties: properties, geometry: geometry}; } function object(topology, o) { var transformPoint = transform(topology.transform), arcs = topology.arcs; function arc$$1(i, points) { if (points.length) points.pop(); for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length; k < n; ++k) { points.push(transformPoint(a[k], k)); } if (i < 0) reverse(points, n); } function point(p) { return transformPoint(p); } function line$$1(arcs) { var points = []; for (var i = 0, n = arcs.length; i < n; ++i) arc$$1(arcs[i], points); if (points.length < 2) points.push(points[0]); // This should never happen per the specification. return points; } function ring(arcs) { var points = line$$1(arcs); while (points.length < 4) points.push(points[0]); // This may happen if an arc has only two points. return points; } function polygon(arcs) { return arcs.map(ring); } function geometry(o) { var type = o.type, coordinates; switch (type) { case "GeometryCollection": return {type: type, geometries: o.geometries.map(geometry)}; case "Point": coordinates = point(o.coordinates); break; case "MultiPoint": coordinates = o.coordinates.map(point); break; case "LineString": coordinates = line$$1(o.arcs); break; case "MultiLineString": coordinates = o.arcs.map(line$$1); break; case "Polygon": coordinates = polygon(o.arcs); break; case "MultiPolygon": coordinates = o.arcs.map(polygon); break; default: return null; } return {type: type, coordinates: coordinates}; } return geometry(o); } var stitch = function(topology, arcs) { var stitchedArcs = {}, fragmentByStart = {}, fragmentByEnd = {}, fragments = [], emptyIndex = -1; // Stitch empty arcs first, since they may be subsumed by other arcs. arcs.forEach(function(i, j) { var arc$$1 = topology.arcs[i < 0 ? ~i : i], t; if (arc$$1.length < 3 && !arc$$1[1][0] && !arc$$1[1][1]) { t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; } }); arcs.forEach(function(i) { var e = ends(i), start = e[0], end = e[1], f, g; if (f = fragmentByEnd[start]) { delete fragmentByEnd[f.end]; f.push(i); f.end = end; if (g = fragmentByStart[end]) { delete fragmentByStart[g.start]; var fg = g === f ? f : f.concat(g); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else if (f = fragmentByStart[end]) { delete fragmentByStart[f.start]; f.unshift(i); f.start = start; if (g = fragmentByEnd[start]) { delete fragmentByEnd[g.end]; var gf = g === f ? f : g.concat(f); fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else { f = [i]; fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; } }); function ends(i) { var arc$$1 = topology.arcs[i < 0 ? ~i : i], p0 = arc$$1[0], p1; if (topology.transform) p1 = [0, 0], arc$$1.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); else p1 = arc$$1[arc$$1.length - 1]; return i < 0 ? [p1, p0] : [p0, p1]; } function flush(fragmentByEnd, fragmentByStart) { for (var k in fragmentByEnd) { var f = fragmentByEnd[k]; delete fragmentByStart[f.start]; delete f.start; delete f.end; f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); fragments.push(f); } } flush(fragmentByEnd, fragmentByStart); flush(fragmentByStart, fragmentByEnd); arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); return fragments; }; var mesh = function(topology) { return object(topology, meshArcs.apply(this, arguments)); }; function meshArcs(topology, object$$1, filter) { var arcs, i, n; if (arguments.length > 1) arcs = extractArcs(topology, object$$1, filter); else for (i = 0, arcs = new Array(n = topology.arcs.length); i < n; ++i) arcs[i] = i; return {type: "MultiLineString", arcs: stitch(topology, arcs)}; } function extractArcs(topology, object$$1, filter) { var arcs = [], geomsByArc = [], geom; function extract0(i) { var j = i < 0 ? ~i : i; (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); } function extract1(arcs) { arcs.forEach(extract0); } function extract2(arcs) { arcs.forEach(extract1); } function extract3(arcs) { arcs.forEach(extract2); } function geometry(o) { switch (geom = o, o.type) { case "GeometryCollection": o.geometries.forEach(geometry); break; case "LineString": extract1(o.arcs); break; case "MultiLineString": case "Polygon": extract2(o.arcs); break; case "MultiPolygon": extract3(o.arcs); break; } } geometry(object$$1); geomsByArc.forEach(filter == null ? function(geoms) { arcs.push(geoms[0].i); } : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); return arcs; } var bisect$1 = function(a, x) { var lo = 0, hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (a[mid] < x) lo = mid + 1; else hi = mid; } return lo; }; var topojson = function(data, format$$1) { var object, property; data = json(data, format$$1); if (format$$1 && (property = format$$1.feature)) { return (object = data.objects[property]) ? feature(data, object).features : error$1('Invalid TopoJSON object: ' + property); } else if (format$$1 && (property = format$$1.mesh)) { return (object = data.objects[property]) ? [mesh(data, object)] : error$1('Invalid TopoJSON object: ' + property); } error$1('Missing TopoJSON feature or mesh parameter.'); }; var formats = { dsv: dsv, csv: delimitedFormat(','), tsv: delimitedFormat('\t'), json: json, topojson: topojson }; var formats$1 = function(name, format$$1) { if (arguments.length > 1) { formats[name] = format$$1; return this; } else { return formats.hasOwnProperty(name) ? formats[name] : null; } }; var read = function(data, schema, dateParse) { schema = schema || {}; var reader = formats$1(schema.type || 'json'); if (!reader) error$1('Unknown data format type: ' + schema.type); data = reader(data, schema); if (schema.parse) parse(data, schema.parse, dateParse); if (data.hasOwnProperty('columns')) delete data.columns; return data; }; function parse(data, types, dateParse) { if (!data.length) return; // early exit for empty data dateParse = dateParse || d3TimeFormat.timeParse; var fields = data.columns || Object.keys(data[0]), parsers, datum, field$$1, i, j, n, m; if (types === 'auto') types = inferTypes(data, fields); fields = Object.keys(types); parsers = fields.map(function(field$$1) { var type = types[field$$1], parts, pattern; if (type && (type.indexOf('date:') === 0 || type.indexOf('utc:') === 0)) { parts = type.split(/:(.+)?/, 2); // split on first : pattern = parts[1]; if ((pattern[0] === '\'' && pattern[pattern.length-1] === '\'') || (pattern[0] === '"' && pattern[pattern.length-1] === '"')) { pattern = pattern.slice(1, -1); } return parts[0] === 'utc' ? d3TimeFormat.utcParse(pattern) : dateParse(pattern); } if (!typeParsers[type]) { throw Error('Illegal format pattern: ' + field$$1 + ':' + type); } return typeParsers[type]; }); for (i=0, n=data.length, m=fields.length; i<n; ++i) { datum = data[i]; for (j=0; j<m; ++j) { field$$1 = fields[j]; datum[field$$1] = parsers[j](datum[field$$1]); } } } function ingest$1(target, data, format$$1) { return this.pulse(target, this.changeset().insert(read(data, format$$1))); } function loadPending(df) { var accept, reject, pending = new Promise(function(a, r) { accept = a; reject = r; }); pending.requests = 0; pending.done = function() { if (--pending.requests === 0) { df.runAfter(function() { df._pending = null; try { df.run(); accept(df); } catch (err) { reject(err); } }); } }; return (df._pending = pending); } function request$1(target, url, format$$1) { var df = this, pending = df._pending || loadPending(df); pending.requests += 1; df.loader() .load(url, {context:'dataflow'}) .then( function(data) { df.ingest(target, data, format$$1); }, function(error) { df.error('Loading failed', url, error); }) .catch( function(error) { df.error('Data ingestion failed', url, error); }) .then(pending.done, pending.done); } var SKIP$1 = {skip: true}; /** * Perform operator updates in response to events. Applies an * update function to compute a new operator value. If the update function * returns a {@link ChangeSet}, the operator will be pulsed with those tuple * changes. Otherwise, the operator value will be updated to the return value. * @param {EventStream|Operator} source - The event source to react to. * This argument can be either an EventStream or an Operator. * @param {Operator|function(object):Operator} target - The operator to update. * This argument can either be an Operator instance or (if the source * argument is an EventStream), a function that accepts an event object as * input and returns an Operator to target. * @param {function(Parameters,Event): *} [update] - Optional update function * to compute the new operator value, or a literal value to set. Update * functions expect to receive a parameter object and event as arguments. * This function can either return a new operator value or (if the source * argument is an EventStream) a {@link ChangeSet} instance to pulse * the target operator with tuple changes. * @param {object} [params] - The update function parameters. * @param {object} [options] - Additional options hash. If not overridden, * updated operators will be skipped by default. * @param {boolean} [options.skip] - If true, the operator will * be skipped: it will not be evaluated, but its dependents will be. * @param {boolean} [options.force] - If true, the operator will * be re-evaluated even if its value has not changed. * @return {Dataflow} */ var on = function(source, target, update, params, options) { var fn = source instanceof Operator ? onOperator : onStream; fn(this, source, target, update, params, options); return this; }; function onStream(df, stream, target, update, params, options) { var opt = extend({}, options, SKIP$1), func, op; if (!isFunction(target)) target = constant(target); if (update === undefined) { func = function(e) { df.touch(target(e)); }; } else if (isFunction(update)) { op = new Operator(null, update, params, false); func = function(e) { var v, t = target(e); op.evaluate(e); isChangeSet(v = op.value) ? df.pulse(t, v, options) : df.update(t, v, opt); }; } else { func = function(e) { df.update(target(e), update, opt); }; } stream.apply(func); } function onOperator(df, source, target, update, params, options) { var func, op; if (update === undefined) { op = target; } else { func = isFunction(update) ? update : constant(update); update = !target ? func : function(_$$1, pulse) { var value = func(_$$1, pulse); return target.skip() ? value : (target.skip(true).value = value); }; op = new Operator(null, update, params, false); op.modified(options && options.force); op.rank = 0; if (target) { op.skip(true); // skip first invocation op.value = target.value; op.targets().add(target); } } source.targets().add(op); } /** * Assigns a rank to an operator. Ranks are assigned in increasing order * by incrementing an internal rank counter. * @param {Operator} op - The operator to assign a rank. */ function rank(op) { op.rank = ++this._rank; } /** * Re-ranks an operator and all downstream target dependencies. This * is necessary when upstream depencies of higher rank are added to * a target operator. * @param {Operator} op - The operator to re-rank. */ function rerank(op) { var queue = [op], cur, list, i; while (queue.length) { this.rank(cur = queue.pop()); if (list = cur._targets) { for (i=list.length; --i >= 0;) { queue.push(cur = list[i]); if (cur === op) error$1('Cycle detected in dataflow graph.'); } } } } /** * Sentinel value indicating pulse propagation should stop. */ var StopPropagation = {}; // Pulse visit type flags var ADD = (1 << 0); var REM = (1 << 1); var MOD = (1 << 2); var ADD_REM = ADD | REM; var ADD_MOD = ADD | MOD; var ALL = ADD | REM | MOD; var REFLOW = (1 << 3); var SOURCE = (1 << 4); var NO_SOURCE = (1 << 5); var NO_FIELDS = (1 << 6); /** * A Pulse enables inter-operator communication during a run of the * dataflow graph. In addition to the current timestamp, a pulse may also * contain a change-set of added, removed or modified data tuples, as well as * a pointer to a full backing data source. Tuple change sets may not * be fully materialized; for example, to prevent needless array creation * a change set may include larger arrays and corresponding filter functions. * The pulse provides a {@link visit} method to enable proper and efficient * iteration over requested data tuples. * * In addition, each pulse can track modification flags for data tuple fields. * Responsible transform operators should call the {@link modifies} method to * indicate changes to data fields. The {@link modified} method enables * querying of this modification state. * * @constructor * @param {Dataflow} dataflow - The backing dataflow instance. * @param {number} stamp - The current propagation timestamp. * @param {string} [encode] - An optional encoding set name, which is then * accessible as Pulse.encode. Operators can respond to (or ignore) this * setting as appropriate. This parameter can be used in conjunction with * the Encode transform in the vega-encode module. */ function Pulse(dataflow, stamp, encode) { this.dataflow = dataflow; this.stamp = stamp == null ? -1 : stamp; this.add = []; this.rem = []; this.mod = []; this.fields = null; this.encode = encode || null; } var prototype$4 = Pulse.prototype; /** * Sentinel value indicating pulse propagation should stop. */ prototype$4.StopPropagation = StopPropagation; /** * Boolean flag indicating ADD (added) tuples. */ prototype$4.ADD = ADD; /** * Boolean flag indicating REM (removed) tuples. */ prototype$4.REM = REM; /** * Boolean flag indicating MOD (modified) tuples. */ prototype$4.MOD = MOD; /** * Boolean flag indicating ADD (added) and REM (removed) tuples. */ prototype$4.ADD_REM = ADD_REM; /** * Boolean flag indicating ADD (added) and MOD (modified) tuples. */ prototype$4.ADD_MOD = ADD_MOD; /** * Boolean flag indicating ADD, REM and MOD tuples. */ prototype$4.ALL = ALL; /** * Boolean flag indicating all tuples in a data source * except for the ADD, REM and MOD tuples. */ prototype$4.REFLOW = REFLOW; /** * Boolean flag indicating a 'pass-through' to a * backing data source, ignoring ADD, REM and MOD tuples. */ prototype$4.SOURCE = SOURCE; /** * Boolean flag indicating that source data should be * suppressed when creating a forked pulse. */ prototype$4.NO_SOURCE = NO_SOURCE; /** * Boolean flag indicating that field modifications should be * suppressed when creating a forked pulse. */ prototype$4.NO_FIELDS = NO_FIELDS; /** * Creates a new pulse based on the values of this pulse. * The dataflow, time stamp and field modification values are copied over. * By default, new empty ADD, REM and MOD arrays are created. * @param {number} flags - Integer of boolean flags indicating which (if any) * tuple arrays should be copied to the new pulse. The supported flag values * are ADD, REM and MOD. Array references are copied directly: new array * instances are not created. * @return {Pulse} - The forked pulse instance. * @see init */ prototype$4.fork = function(flags) { return new Pulse(this.dataflow).init(this, flags); }; /** * Returns a pulse that adds all tuples from a backing source. This is * useful for cases where operators are added to a dataflow after an * upstream data pipeline has already been processed, ensuring that * new operators can observe all tuples within a stream. * @return {Pulse} - A pulse instance with all source tuples included * in the add array. If the current pulse already has all source * tuples in its add array, it is returned directly. If the current * pulse does not have a backing source, it is returned directly. */ prototype$4.addAll = function() { var p = this; if (!this.source || this.source.length === this.add.length) { return p; } else { p = new Pulse(this.dataflow).init(this); p.add = p.source; return p; } }; /** * Initialize this pulse based on the values of another pulse. This method * is used internally by {@link fork} to initialize a new forked tuple. * The dataflow, time stamp and field modification values are copied over. * By default, new empty ADD, REM and MOD arrays are created. * @param {Pulse} src - The source pulse to copy from. * @param {number} flags - Integer of boolean flags indicating which (if any) * tuple arrays should be copied to the new pulse. The supported flag values * are ADD, REM and MOD. Array references are copied directly: new array * instances are not created. By default, source data arrays are copied * to the new pulse. Use the NO_SOURCE flag to enforce a null source. * @return {Pulse} - Returns this Pulse instance. */ prototype$4.init = function(src, flags) { var p = this; p.stamp = src.stamp; p.encode = src.encode; if (src.fields && !(flags & NO_FIELDS)) { p.fields = src.fields; } if (flags & ADD) { p.addF = src.addF; p.add = src.add; } else { p.addF = null; p.add = []; } if (flags & REM) { p.remF = src.remF; p.rem = src.rem; } else { p.remF = null; p.rem = []; } if (flags & MOD) { p.modF = src.modF; p.mod = src.mod; } else { p.modF = null; p.mod = []; } if (flags & NO_SOURCE) { p.srcF = null; p.source = null; } else { p.srcF = src.srcF; p.source = src.source; } return p; }; /** * Schedules a function to run after pulse propagation completes. * @param {function} func - The function to run. */ prototype$4.runAfter = function(func) { this.dataflow.runAfter(func); }; /** * Indicates if tuples have been added, removed or modified. * @param {number} [flags] - The tuple types (ADD, REM or MOD) to query. * Defaults to ALL, returning true if any tuple type has changed. * @return {boolean} - Returns true if one or more queried tuple types have * changed, false otherwise. */ prototype$4.changed = function(flags) { var f = flags || ALL; return ((f & ADD) && this.add.length) || ((f & REM) && this.rem.length) || ((f & MOD) && this.mod.length); }; /** * Forces a "reflow" of tuple values, such that all tuples in the backing * source are added to the MOD set, unless already present in the ADD set. * @param {boolean} [fork=false] - If true, returns a forked copy of this * pulse, and invokes reflow on that derived pulse. * @return {Pulse} - The reflowed pulse instance. */ prototype$4.reflow = function(fork) { if (fork) return this.fork(ALL).reflow(); var len = this.add.length, src = this.source && this.source.length; if (src && src !== len) { this.mod = this.source; if (len) this.filter(MOD, filter(this, ADD)); } return this; }; /** * Marks one or more data field names as modified to assist dependency * tracking and incremental processing by transform operators. * @param {string|Array<string>} _ - The field(s) to mark as modified. * @return {Pulse} - This pulse instance. */ prototype$4.modifies = function(_$$1) { var fields = array(_$$1), hash = this.fields || (this.fields = {}); fields.forEach(function(f) { hash[f] = true; }); return this; }; /** * Checks if one or more data fields have been modified during this pulse * propagation timestamp. * @param {string|Array<string>} _ - The field(s) to check for modified. * @return {boolean} - Returns true if any of the provided fields has been * marked as modified, false otherwise. */ prototype$4.modified = function(_$$1) { var fields = this.fields; return !(this.mod.length && fields) ? false : !arguments.length ? !!fields : isArray(_$$1) ? _$$1.some(function(f) { return fields[f]; }) : fields[_$$1]; }; /** * Adds a filter function to one more tuple sets. Filters are applied to * backing tuple arrays, to determine the actual set of tuples considered * added, removed or modified. They can be used to delay materialization of * a tuple set in order to avoid expensive array copies. In addition, the * filter functions can serve as value transformers: unlike standard predicate * function (which return boolean values), Pulse filters should return the * actual tuple value to process. If a tuple set is already filtered, the * new filter function will be appended into a conjuntive ('and') query. * @param {number} flags - Flags indicating the tuple set(s) to filter. * @param {function(*):object} filter - Filter function that will be applied * to the tuple set array, and should return a data tuple if the value * should be included in the tuple set, and falsy (or null) otherwise. * @return {Pulse} - Returns this pulse instance. */ prototype$4.filter = function(flags, filter) { var p = this; if (flags & ADD) p.addF = addFilter(p.addF, filter); if (flags & REM) p.remF = addFilter(p.remF, filter); if (flags & MOD) p.modF = addFilter(p.modF, filter); if (flags & SOURCE) p.srcF = addFilter(p.srcF, filter); return p; }; function addFilter(a, b) { return a ? function(t,i) { return a(t,i) && b(t,i); } : b; } /** * Materialize one or more tuple sets in this pulse. If the tuple set(s) have * a registered filter function, it will be applied and the tuple set(s) will * be replaced with materialized tuple arrays. * @param {number} flags - Flags indicating the tuple set(s) to materialize. * @return {Pulse} - Returns this pulse instance. */ prototype$4.materialize = function(flags) { flags = flags || ALL; var p = this; if ((flags & ADD) && p.addF) { p.add = materialize(p.add, p.addF); p.addF = null; } if ((flags & REM) && p.remF) { p.rem = materialize(p.rem, p.remF); p.remF = null; } if ((flags & MOD) && p.modF) { p.mod = materialize(p.mod, p.modF); p.modF = null; } if ((flags & SOURCE) && p.srcF) { p.source = p.source.filter(p.srcF); p.srcF = null; } return p; }; function materialize(data, filter) { var out = []; visitArray(data, filter, function(_$$1) { out.push(_$$1); }); return out; } function filter(pulse, flags) { var map = {}; pulse.visit(flags, function(t) { map[tupleid(t)] = 1; }); return function(t) { return map[tupleid(t)] ? null : t; }; } /** * Visit one or more tuple sets in this pulse. * @param {number} flags - Flags indicating the tuple set(s) to visit. * Legal values are ADD, REM, MOD and SOURCE (if a backing data source * has been set). * @param {function(object):*} - Visitor function invoked per-tuple. * @return {Pulse} - Returns this pulse instance. */ prototype$4.visit = function(flags, visitor) { var p = this, v = visitor, src, sum$$1; if (flags & SOURCE) { visitArray(p.source, p.srcF, v); return p; } if (flags & ADD) visitArray(p.add, p.addF, v); if (flags & REM) visitArray(p.rem, p.remF, v); if (flags & MOD) visitArray(p.mod, p.modF, v); if ((flags & REFLOW) && (src = p.source)) { sum$$1 = p.add.length + p.mod.length; if (sum$$1 === src.length) { // do nothing } else if (sum$$1) { visitArray(src, filter(p, ADD_MOD), v); } else { // if no add/rem/mod tuples, visit source visitArray(src, p.srcF, v); } } return p; }; /** * Represents a set of multiple pulses. Used as input for operators * that accept multiple pulses at a time. Contained pulses are * accessible via the public "pulses" array property. This pulse doe * not carry added, removed or modified tuples directly. However, * the visit method can be used to traverse all such tuples contained * in sub-pulses with a timestamp matching this parent multi-pulse. * @constructor * @param {Dataflow} dataflow - The backing dataflow instance. * @param {number} stamp - The timestamp. * @param {Array<Pulse>} pulses - The sub-pulses for this multi-pulse. */ function MultiPulse(dataflow, stamp, pulses, encode) { var p = this, c = 0, pulse, hash, i, n, f; this.dataflow = dataflow; this.stamp = stamp; this.fields = null; this.encode = encode || null; this.pulses = pulses; for (i=0, n=pulses.length; i<n; ++i) { pulse = pulses[i]; if (pulse.stamp !== stamp) continue; if (pulse.fields) { hash = p.fields || (p.fields = {}); for (f in pulse.fields) { hash[f] = 1; } } if (pulse.changed(p.ADD)) c |= p.ADD; if (pulse.changed(p.REM)) c |= p.REM; if (pulse.changed(p.MOD)) c |= p.MOD; } this.changes = c; } var prototype$5 = inherits(MultiPulse, Pulse); /** * Creates a new pulse based on the values of this pulse. * The dataflow, time stamp and field modification values are copied over. * @return {Pulse} */ prototype$5.fork = function(flags) { var p = new Pulse(this.dataflow).init(this, flags & this.NO_FIELDS); if (flags !== undefined) { if (flags & p.ADD) { this.visit(p.ADD, function(t) { return p.add.push(t); }); } if (flags & p.REM) { this.visit(p.REM, function(t) { return p.rem.push(t); }); } if (flags & p.MOD) { this.visit(p.MOD, function(t) { return p.mod.push(t); }); } } return p; }; prototype$5.changed = function(flags) { return this.changes & flags; }; prototype$5.modified = function(_$$1) { var p = this, fields = p.fields; return !(fields && (p.changes & p.MOD)) ? 0 : isArray(_$$1) ? _$$1.some(function(f) { return fields[f]; }) : fields[_$$1]; }; prototype$5.filter = function() { error$1('MultiPulse does not support filtering.'); }; prototype$5.materialize = function() { error$1('MultiPulse does not support materialization.'); }; prototype$5.visit = function(flags, visitor) { var p = this, pulses = p.pulses, n = pulses.length, i = 0; if (flags & p.SOURCE) { for (; i<n; ++i) { pulses[i].visit(flags, visitor); } } else { for (; i<n; ++i) { if (pulses[i].stamp === p.stamp) { pulses[i].visit(flags, visitor); } } } return p; }; /** * Runs the dataflow. This method will increment the current timestamp * and process all updated, pulsed and touched operators. When run for * the first time, all registered operators will be processed. If there * are pending data loading operations, this method will return immediately * without evaluating the dataflow. Instead, the dataflow will be * asynchronously invoked when data loading completes. To track when dataflow * evaluation completes, use the {@link runAsync} method instead. * @param {string} [encode] - The name of an encoding set to invoke during * propagation. This value is added to generated Pulse instances; * operators can then respond to (or ignore) this setting as appropriate. * This parameter can be used in conjunction with the Encode transform in * the vega-encode module. */ function run(encode) { var df = this, count = 0, level = df.logLevel(), op, next, dt, error; if (df._pending) { df.info('Awaiting requests, delaying dataflow run.'); return 0; } if (df._pulse) { df.error('Dataflow invoked recursively. Use the runAfter method to queue invocation.'); return 0; } if (!df._touched.length) { df.info('Dataflow invoked, but nothing to do.'); return 0; } df._pulse = new Pulse(df, ++df._clock, encode); if (level >= Info) { dt = Date.now(); df.debug('-- START PROPAGATION (' + df._clock + ') -----'); } // initialize queue, reset touched operators df._touched.forEach(function(op) { df._enqueue(op, true); }); df._touched = UniqueList(id); try { while (df._heap.size() > 0) { op = df._heap.pop(); // re-queue if rank changes if (op.rank !== op.qrank) { df._enqueue(op, true); continue; } // otherwise, evaluate the operator next = op.run(df._getPulse(op, encode)); if (level >= Debug) { df.debug(op.id, next === StopPropagation ? 'STOP' : next, op); } // propagate the pulse if (next !== StopPropagation) { df._pulse = next; if (op._targets) op._targets.forEach(function(op) { df._enqueue(op); }); } // increment visit counter ++count; } } catch (err) { error = err; } // reset pulse map df._pulses = {}; df._pulse = null; if (level >= Info) { dt = Date.now() - dt; df.info('> Pulse ' + df._clock + ': ' + count + ' operators; ' + dt + 'ms'); } if (error) { df._postrun = []; df.error(error); } if (df._onrun) { try { df._onrun(df, count, error); } catch (err) { df.error(err); } } // invoke callbacks queued via runAfter if (df._postrun.length) { var postrun = df._postrun; df._postrun = []; postrun.forEach(function(f) { try { f(df); } catch (err) { df.error(err); } }); } return count; } /** * Runs the dataflow and returns a Promise that resolves when the * propagation cycle completes. The standard run method may exit early * if there are pending data loading operations. In contrast, this * method returns a Promise to allow callers to receive notification * when dataflow evaluation completes. * @return {Promise} - A promise that resolves to this dataflow. */ function runAsync() { return this._pending || Promise.resolve(this.run()); } /** * Schedules a callback function to be invoked after the current pulse * propagation completes. If no propagation is currently occurring, * the function is invoked immediately. * @param {function(Dataflow)} callback - The callback function to run. * The callback will be invoked with this Dataflow instance as its * sole argument. * @param {boolean} enqueue - A boolean flag indicating that the * callback should be queued up to run after the next propagation * cycle, suppressing immediate invovation when propagation is not * currently occurring. */ function runAfter(callback, enqueue) { if (this._pulse || enqueue) { // pulse propagation is currently running, queue to run after this._postrun.push(callback); } else { // pulse propagation already complete, invoke immediately try { callback(this); } catch (err) { this.error(err); } } } /** * Enqueue an operator into the priority queue for evaluation. The operator * will be enqueued if it has no registered pulse for the current cycle, or if * the force argument is true. Upon enqueue, this method also sets the * operator's qrank to the current rank value. * @param {Operator} op - The operator to enqueue. * @param {boolean} [force] - A flag indicating if the operator should be * forceably added to the queue, even if it has already been previously * enqueued during the current pulse propagation. This is useful when the * dataflow graph is dynamically modified and the operator rank changes. */ function enqueue(op, force) { var p = !this._pulses[op.id]; if (p) this._pulses[op.id] = this._pulse; if (p || force) { op.qrank = op.rank; this._heap.push(op); } } /** * Provide a correct pulse for evaluating an operator. If the operator has an * explicit source operator, we will try to pull the pulse(s) from it. * If there is an array of source operators, we build a multi-pulse. * Otherwise, we return a current pulse with correct source data. * If the pulse is the pulse map has an explicit target set, we use that. * Else if the pulse on the upstream source operator is current, we use that. * Else we use the pulse from the pulse map, but copy the source tuple array. * @param {Operator} op - The operator for which to get an input pulse. * @param {string} [encode] - An (optional) encoding set name with which to * annotate the returned pulse. See {@link run} for more information. */ function getPulse(op, encode) { var s = op.source, stamp = this._clock, p; if (s && isArray(s)) { p = s.map(function(_$$1) { return _$$1.pulse; }); return new MultiPulse(this, stamp, p, encode); } p = this._pulses[op.id]; if (s) { s = s.pulse; if (!s || s === StopPropagation) { p.source = []; } else if (s.stamp === stamp && p.target !== op) { p = s; } else { p.source = s.source; } } return p; } var NO_OPT = {skip: false, force: false}; /** * Touches an operator, scheduling it to be evaluated. If invoked outside of * a pulse propagation, the operator will be evaluated the next time this * dataflow is run. If invoked in the midst of pulse propagation, the operator * will be queued for evaluation if and only if the operator has not yet been * evaluated on the current propagation timestamp. * @param {Operator} op - The operator to touch. * @param {object} [options] - Additional options hash. * @param {boolean} [options.skip] - If true, the operator will * be skipped: it will not be evaluated, but its dependents will be. * @return {Dataflow} */ function touch(op, options) { var opt = options || NO_OPT; if (this._pulse) { // if in midst of propagation, add to priority queue this._enqueue(op); } else { // otherwise, queue for next propagation this._touched.add(op); } if (opt.skip) op.skip(true); return this; } /** * Updates the value of the given operator. * @param {Operator} op - The operator to update. * @param {*} value - The value to set. * @param {object} [options] - Additional options hash. * @param {boolean} [options.force] - If true, the operator will * be re-evaluated even if its value has not changed. * @param {boolean} [options.skip] - If true, the operator will * be skipped: it will not be evaluated, but its dependents will be. * @return {Dataflow} */ function update(op, value, options) { var opt = options || NO_OPT; if (op.set(value) || opt.force) { this.touch(op, opt); } return this; } /** * Pulses an operator with a changeset of tuples. If invoked outside of * a pulse propagation, the pulse will be applied the next time this * dataflow is run. If invoked in the midst of pulse propagation, the pulse * will be added to the set of active pulses and will be applied if and * only if the target operator has not yet been evaluated on the current * propagation timestamp. * @param {Operator} op - The operator to pulse. * @param {ChangeSet} value - The tuple changeset to apply. * @param {object} [options] - Additional options hash. * @param {boolean} [options.skip] - If true, the operator will * be skipped: it will not be evaluated, but its dependents will be. * @return {Dataflow} */ function pulse(op, changeset, options) { this.touch(op, options || NO_OPT); var p = new Pulse(this, this._clock + (this._pulse ? 0 : 1)), t = op.pulse && op.pulse.source || []; p.target = op; this._pulses[op.id] = changeset.pulse(p, t); return this; } function Heap(comparator) { this.cmp = comparator; this.nodes = []; } var prototype$6 = Heap.prototype; prototype$6.size = function() { return this.nodes.length; }; prototype$6.clear = function() { this.nodes = []; return this; }; prototype$6.peek = function() { return this.nodes[0]; }; prototype$6.push = function(x) { var array = this.nodes; array.push(x); return siftdown(array, 0, array.length-1, this.cmp); }; prototype$6.pop = function() { var array = this.nodes, last = array.pop(), item; if (array.length) { item = array[0]; array[0] = last; siftup(array, 0, this.cmp); } else { item = last; } return item; }; prototype$6.replace = function(item) { var array = this.nodes, retval = array[0]; array[0] = item; siftup(array, 0, this.cmp); return retval; }; prototype$6.pushpop = function(item) { var array = this.nodes, ref = array[0]; if (array.length && this.cmp(ref, item) < 0) { array[0] = item; item = ref; siftup(array, 0, this.cmp); } return item; }; function siftdown(array, start, idx, cmp) { var item, parent, pidx; item = array[idx]; while (idx > start) { pidx = (idx - 1) >> 1; parent = array[pidx]; if (cmp(item, parent) < 0) { array[idx] = parent; idx = pidx; continue; } break; } return (array[idx] = item); } function siftup(array, idx, cmp) { var start = idx, end = array.length, item = array[idx], cidx = 2 * idx + 1, ridx; while (cidx < end) { ridx = cidx + 1; if (ridx < end && cmp(array[cidx], array[ridx]) >= 0) { cidx = ridx; } array[idx] = array[cidx]; idx = cidx; cidx = 2 * idx + 1; } array[idx] = item; return siftdown(array, start, idx, cmp); } /** * A dataflow graph for reactive processing of data streams. * @constructor */ function Dataflow() { this._log = logger(); this.logLevel(Error$1); this._clock = 0; this._rank = 0; try { this._loader = loader(); } catch (e) { // do nothing if loader module is unavailable } this._touched = UniqueList(id); this._pulses = {}; this._pulse = null; this._heap = new Heap(function(a, b) { return a.qrank - b.qrank; }); this._postrun = []; } var prototype = Dataflow.prototype; /** * The current timestamp of this dataflow. This value reflects the * timestamp of the previous dataflow run. The dataflow is initialized * with a stamp value of 0. The initial run of the dataflow will have * a timestap of 1, and so on. This value will match the * {@link Pulse.stamp} property. * @return {number} - The current timestamp value. */ prototype.stamp = function() { return this._clock; }; /** * Gets or sets the loader instance to use for data file loading. A * loader object must provide a "load" method for loading files and a * "sanitize" method for checking URL/filename validity. Both methods * should accept a URI and options hash as arguments, and return a Promise * that resolves to the loaded file contents (load) or a hash containing * sanitized URI data with the sanitized url assigned to the "href" property * (sanitize). * @param {object} _ - The loader instance to use. * @return {object|Dataflow} - If no arguments are provided, returns * the current loader instance. Otherwise returns this Dataflow instance. */ prototype.loader = function(_$$1) { if (arguments.length) { this._loader = _$$1; return this; } else { return this._loader; } }; /** * Empty entry threshold for garbage cleaning. Map data structures will * perform cleaning once the number of empty entries exceeds this value. */ prototype.cleanThreshold = 1e4; // OPERATOR REGISTRATION prototype.add = add; prototype.connect = connect; prototype.rank = rank; prototype.rerank = rerank; // OPERATOR UPDATES prototype.pulse = pulse; prototype.touch = touch; prototype.update = update; prototype.changeset = changeset; // DATA LOADING prototype.ingest = ingest$1; prototype.request = request$1; // EVENT HANDLING prototype.events = events; prototype.on = on; // PULSE PROPAGATION prototype.run = run; prototype.runAsync = runAsync; prototype.runAfter = runAfter; prototype._enqueue = enqueue; prototype._getPulse = getPulse; // LOGGING AND ERROR HANDLING function logMethod(method) { return function() { return this._log[method].apply(this, arguments); }; } /** * Logs an error message. By default, logged messages are written to console * output. The message will only be logged if the current log level is high * enough to permit error messages. */ prototype.error = logMethod('error'); /** * Logs a warning message. By default, logged messages are written to console * output. The message will only be logged if the current log level is high * enough to permit warning messages. */ prototype.warn = logMethod('warn'); /** * Logs a information message. By default, logged messages are written to * console output. The message will only be logged if the current log level is * high enough to permit information messages. */ prototype.info = logMethod('info'); /** * Logs a debug message. By default, logged messages are written to console * output. The message will only be logged if the current log level is high * enough to permit debug messages. */ prototype.debug = logMethod('debug'); /** * Get or set the current log level. If an argument is provided, it * will be used as the new log level. * @param {number} [level] - Should be one of None, Warn, Info * @return {number} - The current log level. */ prototype.logLevel = logMethod('level'); /** * Abstract class for operators that process data tuples. * Subclasses must provide a {@link transform} method for operator processing. * @constructor * @param {*} [init] - The initial value for this operator. * @param {object} [params] - The parameters for this operator. * @param {Operator} [source] - The operator from which to receive pulses. */ function Transform(init, params) { Operator.call(this, init, null, params); } var prototype$7 = inherits(Transform, Operator); /** * Overrides {@link Operator.evaluate} for transform operators. * Internally, this method calls {@link evaluate} to perform processing. * If {@link evaluate} returns a falsy value, the input pulse is returned. * This method should NOT be overridden, instead overrride {@link evaluate}. * @param {Pulse} pulse - the current dataflow pulse. * @return the output pulse for this operator (or StopPropagation) */ prototype$7.run = function(pulse) { if (pulse.stamp <= this.stamp) return pulse.StopPropagation; var rv; if (this.skip()) { this.skip(false); } else { rv = this.evaluate(pulse); } rv = rv || pulse; if (rv !== pulse.StopPropagation) this.pulse = rv; this.stamp = pulse.stamp; return rv; }; /** * Overrides {@link Operator.evaluate} for transform operators. * Marshalls parameter values and then invokes {@link transform}. * @param {Pulse} pulse - the current dataflow pulse. * @return {Pulse} The output pulse (or StopPropagation). A falsy return value (including undefined) will let the input pulse pass through. */ prototype$7.evaluate = function(pulse) { var params = this.marshall(pulse.stamp), out = this.transform(params, pulse); params.clear(); return out; }; /** * Process incoming pulses. * Subclasses should override this method to implement transforms. * @param {Parameters} _ - The operator parameter values. * @param {Pulse} pulse - The current dataflow pulse. * @return {Pulse} The output pulse (or StopPropagation). A falsy return * value (including undefined) will let the input pulse pass through. */ prototype$7.transform = function() {}; var transforms = {}; function definition(type) { var t = transform$1(type); return t && t.Definition || null; } function transform$1(type) { type = type && type.toLowerCase(); return transforms.hasOwnProperty(type) ? transforms[type] : null; } // Utilities function multikey(f) { return function(x) { var n = f.length, i = 1, k = String(f[0](x)); for (; i<n; ++i) { k += '|' + f[i](x); } return k; }; } function groupkey(fields) { return !fields || !fields.length ? function() { return ''; } : fields.length === 1 ? fields[0] : multikey(fields); } function measureName(op, field$$1, as) { return as || (op + (!field$$1 ? '' : '_' + field$$1)); } var AggregateOps = { 'values': measure({ name: 'values', init: 'cell.store = true;', set: 'cell.data.values()', idx: -1 }), 'count': measure({ name: 'count', set: 'cell.num' }), 'missing': measure({ name: 'missing', set: 'this.missing' }), 'valid': measure({ name: 'valid', set: 'this.valid' }), 'sum': measure({ name: 'sum', init: 'this.sum = 0;', add: 'this.sum += v;', rem: 'this.sum -= v;', set: 'this.sum' }), 'mean': measure({ name: 'mean', init: 'this.mean = 0;', add: 'var d = v - this.mean; this.mean += d / this.valid;', rem: 'var d = v - this.mean; this.mean -= this.valid ? d / this.valid : this.mean;', set: 'this.mean' }), 'average': measure({ name: 'average', set: 'this.mean', req: ['mean'], idx: 1 }), 'variance': measure({ name: 'variance', init: 'this.dev = 0;', add: 'this.dev += d * (v - this.mean);', rem: 'this.dev -= d * (v - this.mean);', set: 'this.valid > 1 ? this.dev / (this.valid-1) : 0', req: ['mean'], idx: 1 }), 'variancep': measure({ name: 'variancep', set: 'this.valid > 1 ? this.dev / this.valid : 0', req: ['variance'], idx: 2 }), 'stdev': measure({ name: 'stdev', set: 'this.valid > 1 ? Math.sqrt(this.dev / (this.valid-1)) : 0', req: ['variance'], idx: 2 }), 'stdevp': measure({ name: 'stdevp', set: 'this.valid > 1 ? Math.sqrt(this.dev / this.valid) : 0', req: ['variance'], idx: 2 }), 'stderr': measure({ name: 'stderr', set: 'this.valid > 1 ? Math.sqrt(this.dev / (this.valid * (this.valid-1))) : 0', req: ['variance'], idx: 2 }), 'distinct': measure({ name: 'distinct', set: 'cell.data.distinct(this.get)', req: ['values'], idx: 3 }), 'ci0': measure({ name: 'ci0', set: 'cell.data.ci0(this.get)', req: ['values'], idx: 3 }), 'ci1': measure({ name: 'ci1', set: 'cell.data.ci1(this.get)', req: ['values'], idx: 3 }), 'median': measure({ name: 'median', set: 'cell.data.q2(this.get)', req: ['values'], idx: 3 }), 'q1': measure({ name: 'q1', set: 'cell.data.q1(this.get)', req: ['values'], idx: 3 }), 'q3': measure({ name: 'q3', set: 'cell.data.q3(this.get)', req: ['values'], idx: 3 }), 'argmin': measure({ name: 'argmin', init: 'this.argmin = null;', add: 'if (v < this.min) this.argmin = t;', rem: 'if (v <= this.min) this.argmin = null;', set: 'this.argmin || cell.data.argmin(this.get)', req: ['min'], str: ['values'], idx: 3 }), 'argmax': measure({ name: 'argmax', init: 'this.argmax = null;', add: 'if (v > this.max) this.argmax = t;', rem: 'if (v >= this.max) this.argmax = null;', set: 'this.argmax || cell.data.argmax(this.get)', req: ['max'], str: ['values'], idx: 3 }), 'min': measure({ name: 'min', init: 'this.min = null;', add: 'if (v < this.min || this.min === null) this.min = v;', rem: 'if (v <= this.min) this.min = NaN;', set: 'this.min = (isNaN(this.min) ? cell.data.min(this.get) : this.min)', str: ['values'], idx: 4 }), 'max': measure({ name: 'max', init: 'this.max = null;', add: 'if (v > this.max || this.max === null) this.max = v;', rem: 'if (v >= this.max) this.max = NaN;', set: 'this.max = (isNaN(this.max) ? cell.data.max(this.get) : this.max)', str: ['values'], idx: 4 }) }; var ValidAggregateOps = Object.keys(AggregateOps); function createMeasure(op, name) { return AggregateOps[op](name); } function measure(base) { return function(out) { var m = extend({init:'', add:'', rem:'', idx:0}, base); m.out = out || base.name; return m; }; } function compareIndex(a, b) { return a.idx - b.idx; } function resolve(agg, stream) { function collect(m, a) { function helper(r) { if (!m[r]) collect(m, m[r] = AggregateOps[r]()); } if (a.req) a.req.forEach(helper); if (stream && a.str) a.str.forEach(helper); return m; } var map = agg.reduce( collect, agg.reduce(function(m, a) { m[a.name] = a; return m; }, {}) ); var values = [], key$$1; for (key$$1 in map) values.push(map[key$$1]); return values.sort(compareIndex); } function compileMeasures(agg, field$$1) { var get = field$$1 || identity, all = resolve(agg, true), // assume streaming removes may occur init = 'var cell = this.cell; this.valid = 0; this.missing = 0;', ctr = 'this.cell = cell; this.init();', add = 'if(v==null){++this.missing; return;} if(v!==v) return; ++this.valid;', rem = 'if(v==null){--this.missing; return;} if(v!==v) return; --this.valid;', set = 'var cell = this.cell;'; all.forEach(function(a) { init += a.init; add += a.add; rem += a.rem; }); agg.slice().sort(compareIndex).forEach(function(a) { set += 't[\'' + a.out + '\']=' + a.set + ';'; }); set += 'return t;'; ctr = Function('cell', ctr); ctr.prototype.init = Function(init); ctr.prototype.add = Function('v', 't', add); ctr.prototype.rem = Function('v', 't', rem); ctr.prototype.set = Function('t', set); ctr.prototype.get = get; ctr.fields = agg.map(function(_$$1) { return _$$1.out; }); return ctr; } var bin = function(_$$1) { // determine range var maxb = _$$1.maxbins || 20, base = _$$1.base || 10, logb = Math.log(base), div = _$$1.divide || [5, 2], min$$1 = _$$1.extent[0], max$$1 = _$$1.extent[1], span = max$$1 - min$$1, step, level, minstep, precision, v, i, n, eps; if (_$$1.step) { // if step size is explicitly given, use that step = _$$1.step; } else if (_$$1.steps) { // if provided, limit choice to acceptable step sizes v = span / maxb; for (i=0, n=_$$1.steps.length; i < n && _$$1.steps[i] < v; ++i); step = _$$1.steps[Math.max(0, i-1)]; } else { // else use span to determine step size level = Math.ceil(Math.log(maxb) / logb); minstep = _$$1.minstep || 0; step = Math.max( minstep, Math.pow(base, Math.round(Math.log(span) / logb) - level) ); // increase step size if too many bins while (Math.ceil(span/step) > maxb) { step *= base; } // decrease step size if allowed for (i=0, n=div.length; i<n; ++i) { v = step / div[i]; if (v >= minstep && span / v <= maxb) step = v; } } // update precision, min and max v = Math.log(step); precision = v >= 0 ? 0 : ~~(-v / logb) + 1; eps = Math.pow(base, -precision - 1); if (_$$1.nice || _$$1.nice === undefined) { v = Math.floor(min$$1 / step + eps) * step; min$$1 = min$$1 < v ? v - step : v; max$$1 = Math.ceil(max$$1 / step) * step; } return { start: min$$1, stop: max$$1, step: step }; }; var numbers = function(array, f) { var numbers = [], n = array.length, i = -1, a; if (f == null) { while (++i < n) if (!isNaN(a = number(array[i]))) numbers.push(a); } else { while (++i < n) if (!isNaN(a = number(f(array[i], i, array)))) numbers.push(a); } return numbers; }; function number(x) { return x === null ? NaN : +x; } exports.random = Math.random; function setRandom(r) { exports.random = r; } var bootstrapCI = function(array, samples, alpha, f) { var values = numbers(array, f), n = values.length, m = samples, a, i, j, mu; for (j=0, mu=Array(m); j<m; ++j) { for (a=0, i=0; i<n; ++i) { a += values[~~(exports.random() * n)]; } mu[j] = a / n; } return [ d3Array.quantile(mu.sort(d3Array.ascending), alpha/2), d3Array.quantile(mu, 1-(alpha/2)) ]; }; var quartiles = function(array, f) { var values = numbers(array, f); return [ d3Array.quantile(values.sort(d3Array.ascending), 0.25), d3Array.quantile(values, 0.50), d3Array.quantile(values, 0.75) ]; }; var integer = function(min$$1, max$$1) { if (max$$1 == null) { max$$1 = min$$1; min$$1 = 0; } var dist = {}, a, b, d; dist.min = function(_$$1) { if (arguments.length) { a = _$$1 || 0; d = b - a; return dist; } else { return a; } }; dist.max = function(_$$1) { if (arguments.length) { b = _$$1 || 0; d = b - a; return dist; } else { return b; } }; dist.sample = function() { return a + Math.floor(d * exports.random()); }; dist.pdf = function(x) { return (x === Math.floor(x) && x >= a && x < b) ? 1 / d : 0; }; dist.cdf = function(x) { var v = Math.floor(x); return v < a ? 0 : v >= b ? 1 : (v - a + 1) / d; }; dist.icdf = function(p) { return (p >= 0 && p <= 1) ? a - 1 + Math.floor(p * d) : NaN; }; return dist.min(min$$1).max(max$$1); }; var randomNormal = function(mean$$1, stdev) { var mu, sigma, next = NaN, dist = {}; dist.mean = function(_$$1) { if (arguments.length) { mu = _$$1 || 0; next = NaN; return dist; } else { return mu; } }; dist.stdev = function(_$$1) { if (arguments.length) { sigma = _$$1 == null ? 1 : _$$1; next = NaN; return dist; } else { return sigma; } }; dist.sample = function() { var x = 0, y = 0, rds, c; if (next === next) { x = next; next = NaN; return x; } do { x = exports.random() * 2 - 1; y = exports.random() * 2 - 1; rds = x * x + y * y; } while (rds === 0 || rds > 1); c = Math.sqrt(-2 * Math.log(rds) / rds); // Box-Muller transform next = mu + y * c * sigma; return mu + x * c * sigma; }; dist.pdf = function(x) { var exp = Math.exp(Math.pow(x-mu, 2) / (-2 * Math.pow(sigma, 2))); return (1 / (sigma * Math.sqrt(2*Math.PI))) * exp; }; // Approximation from West (2009) // Better Approximations to Cumulative Normal Functions dist.cdf = function(x) { var cd, z = (x - mu) / sigma, Z = Math.abs(z); if (Z > 37) { cd = 0; } else { var sum$$1, exp = Math.exp(-Z*Z/2); if (Z < 7.07106781186547) { sum$$1 = 3.52624965998911e-02 * Z + 0.700383064443688; sum$$1 = sum$$1 * Z + 6.37396220353165; sum$$1 = sum$$1 * Z + 33.912866078383; sum$$1 = sum$$1 * Z + 112.079291497871; sum$$1 = sum$$1 * Z + 221.213596169931; sum$$1 = sum$$1 * Z + 220.206867912376; cd = exp * sum$$1; sum$$1 = 8.83883476483184e-02 * Z + 1.75566716318264; sum$$1 = sum$$1 * Z + 16.064177579207; sum$$1 = sum$$1 * Z + 86.7807322029461; sum$$1 = sum$$1 * Z + 296.564248779674; sum$$1 = sum$$1 * Z + 637.333633378831; sum$$1 = sum$$1 * Z + 793.826512519948; sum$$1 = sum$$1 * Z + 440.413735824752; cd = cd / sum$$1; } else { sum$$1 = Z + 0.65; sum$$1 = Z + 4 / sum$$1; sum$$1 = Z + 3 / sum$$1; sum$$1 = Z + 2 / sum$$1; sum$$1 = Z + 1 / sum$$1; cd = exp / sum$$1 / 2.506628274631; } } return z > 0 ? 1 - cd : cd; }; // Approximation of Probit function using inverse error function. dist.icdf = function(p) { if (p <= 0 || p >= 1) return NaN; var x = 2*p - 1, v = (8 * (Math.PI - 3)) / (3 * Math.PI * (4-Math.PI)), a = (2 / (Math.PI*v)) + (Math.log(1 - Math.pow(x,2)) / 2), b = Math.log(1 - (x*x)) / v, s = (x > 0 ? 1 : -1) * Math.sqrt(Math.sqrt((a*a) - b) - a); return mu + sigma * Math.SQRT2 * s; }; return dist.mean(mean$$1).stdev(stdev); }; // TODO: support for additional kernels? var randomKDE = function(support, bandwidth) { var kernel = randomNormal(), dist = {}, n = 0; dist.data = function(_$$1) { if (arguments.length) { support = _$$1; n = _$$1 ? _$$1.length : 0; return dist.bandwidth(bandwidth); } else { return support; } }; dist.bandwidth = function(_$$1) { if (!arguments.length) return bandwidth; bandwidth = _$$1; if (!bandwidth && support) bandwidth = estimateBandwidth(support); return dist; }; dist.sample = function() { return support[~~(exports.random() * n)] + bandwidth * kernel.sample(); }; dist.pdf = function(x) { for (var y=0, i=0; i<n; ++i) { y += kernel.pdf((x - support[i]) / bandwidth); } return y / bandwidth / n; }; dist.cdf = function(x) { for (var y=0, i=0; i<n; ++i) { y += kernel.cdf((x - support[i]) / bandwidth); } return y / n; }; dist.icdf = function() { throw Error('KDE icdf not supported.'); }; return dist.data(support); }; // Scott, D. W. (1992) Multivariate Density Estimation: // Theory, Practice, and Visualization. Wiley. function estimateBandwidth(array) { var n = array.length, q = quartiles(array), h = (q[2] - q[0]) / 1.34; return 1.06 * Math.min(Math.sqrt(d3Array.variance(array)), h) * Math.pow(n, -0.2); } var randomMixture = function(dists, weights) { var dist = {}, m = 0, w; function normalize(x) { var w = [], sum$$1 = 0, i; for (i=0; i<m; ++i) { sum$$1 += (w[i] = (x[i]==null ? 1 : +x[i])); } for (i=0; i<m; ++i) { w[i] /= sum$$1; } return w; } dist.weights = function(_$$1) { if (arguments.length) { w = normalize(weights = (_$$1 || [])); return dist; } return weights; }; dist.distributions = function(_$$1) { if (arguments.length) { if (_$$1) { m = _$$1.length; dists = _$$1; } else { m = 0; dists = []; } return dist.weights(weights); } return dists; }; dist.sample = function() { var r = exports.random(), d = dists[m-1], v = w[0], i = 0; // first select distribution for (; i<m-1; v += w[++i]) { if (r < v) { d = dists[i]; break; } } // then sample from it return d.sample(); }; dist.pdf = function(x) { for (var p=0, i=0; i<m; ++i) { p += w[i] * dists[i].pdf(x); } return p; }; dist.cdf = function(x) { for (var p=0, i=0; i<m; ++i) { p += w[i] * dists[i].cdf(x); } return p; }; dist.icdf = function() { throw Error('Mixture icdf not supported.'); }; return dist.distributions(dists).weights(weights); }; var randomUniform = function(min$$1, max$$1) { if (max$$1 == null) { max$$1 = (min$$1 == null ? 1 : min$$1); min$$1 = 0; } var dist = {}, a, b, d; dist.min = function(_$$1) { if (arguments.length) { a = _$$1 || 0; d = b - a; return dist; } else { return a; } }; dist.max = function(_$$1) { if (arguments.length) { b = _$$1 || 0; d = b - a; return dist; } else { return b; } }; dist.sample = function() { return a + d * exports.random(); }; dist.pdf = function(x) { return (x >= a && x <= b) ? 1 / d : 0; }; dist.cdf = function(x) { return x < a ? 0 : x > b ? 1 : (x - a) / d; }; dist.icdf = function(p) { return (p >= 0 && p <= 1) ? a + p * d : NaN; }; return dist.min(min$$1).max(max$$1); }; function TupleStore(key$$1) { this._key = key$$1 ? field(key$$1) : tupleid; this.reset(); } var prototype$9 = TupleStore.prototype; prototype$9.reset = function() { this._add = []; this._rem = []; this._ext = null; this._get = null; this._q = null; }; prototype$9.add = function(v) { this._add.push(v); }; prototype$9.rem = function(v) { this._rem.push(v); }; prototype$9.values = function() { this._get = null; if (this._rem.length === 0) return this._add; var a = this._add, r = this._rem, k = this._key, n = a.length, m = r.length, x = Array(n - m), map = {}, i, j, v; // use unique key field to clear removed values for (i=0; i<m; ++i) { map[k(r[i])] = 1; } for (i=0, j=0; i<n; ++i) { if (map[k(v = a[i])]) { map[k(v)] = 0; } else { x[j++] = v; } } this._rem = []; return (this._add = x); }; // memoizing statistics methods prototype$9.distinct = function(get) { var v = this.values(), n = v.length, map = {}, count = 0, s; while (--n >= 0) { s = get(v[n]) + ''; if (!map.hasOwnProperty(s)) { map[s] = 1; ++count; } } return count; }; prototype$9.extent = function(get) { if (this._get !== get || !this._ext) { var v = this.values(), i = extentIndex(v, get); this._ext = [v[i[0]], v[i[1]]]; this._get = get; } return this._ext; }; prototype$9.argmin = function(get) { return this.extent(get)[0] || {}; }; prototype$9.argmax = function(get) { return this.extent(get)[1] || {}; }; prototype$9.min = function(get) { var m = this.extent(get)[0]; return m != null ? get(m) : +Infinity; }; prototype$9.max = function(get) { var m = this.extent(get)[1]; return m != null ? get(m) : -Infinity; }; prototype$9.quartile = function(get) { if (this._get !== get || !this._q) { this._q = quartiles(this.values(), get); this._get = get; } return this._q; }; prototype$9.q1 = function(get) { return this.quartile(get)[0]; }; prototype$9.q2 = function(get) { return this.quartile(get)[1]; }; prototype$9.q3 = function(get) { return this.quartile(get)[2]; }; prototype$9.ci = function(get) { if (this._get !== get || !this._ci) { this._ci = bootstrapCI(this.values(), 1000, 0.05, get); this._get = get; } return this._ci; }; prototype$9.ci0 = function(get) { return this.ci(get)[0]; }; prototype$9.ci1 = function(get) { return this.ci(get)[1]; }; /** * Group-by aggregation operator. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby. * @param {Array<function(object): *>} [params.fields] - An array of accessors to aggregate. * @param {Array<string>} [params.ops] - An array of strings indicating aggregation operations. * @param {Array<string>} [params.as] - An array of output field names for aggregated values. * @param {boolean} [params.cross=false] - A flag indicating that the full * cross-product of groupby values should be generated, including empty cells. * If true, the drop parameter is ignored and empty cells are retained. * @param {boolean} [params.drop=true] - A flag indicating if empty cells should be removed. */ function Aggregate(params) { Transform.call(this, null, params); this._adds = []; // array of added output tuples this._mods = []; // array of modified output tuples this._alen = 0; // number of active added tuples this._mlen = 0; // number of active modified tuples this._drop = true; // should empty aggregation cells be removed this._cross = false; // produce full cross-product of group-by values this._dims = []; // group-by dimension accessors this._dnames = []; // group-by dimension names this._measures = []; // collection of aggregation monoids this._countOnly = false; // flag indicating only count aggregation this._counts = null; // collection of count fields this._prev = null; // previous aggregation cells this._inputs = null; // array of dependent input tuple field names this._outputs = null; // array of output tuple field names } Aggregate.Definition = { "type": "Aggregate", "metadata": {"generates": true, "changes": true}, "params": [ { "name": "groupby", "type": "field", "array": true }, { "name": "ops", "type": "enum", "array": true, "values": ValidAggregateOps }, { "name": "fields", "type": "field", "null": true, "array": true }, { "name": "as", "type": "string", "null": true, "array": true }, { "name": "drop", "type": "boolean", "default": true }, { "name": "cross", "type": "boolean", "default": false }, { "name": "key", "type": "field" } ] }; var prototype$8 = inherits(Aggregate, Transform); prototype$8.transform = function(_$$1, pulse) { var aggr = this, out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), mod; this.stamp = out.stamp; if (this.value && ((mod = _$$1.modified()) || pulse.modified(this._inputs))) { this._prev = this.value; this.value = mod ? this.init(_$$1) : {}; pulse.visit(pulse.SOURCE, function(t) { aggr.add(t); }); } else { this.value = this.value || this.init(_$$1); pulse.visit(pulse.REM, function(t) { aggr.rem(t); }); pulse.visit(pulse.ADD, function(t) { aggr.add(t); }); } // Indicate output fields and return aggregate tuples. out.modifies(this._outputs); // Should empty cells be dropped? aggr._drop = _$$1.drop !== false; // If domain cross-product requested, generate empty cells as needed // and ensure that empty cells are not dropped if (_$$1.cross && aggr._dims.length > 1) { aggr._drop = false; this.cross(); } return aggr.changes(out); }; prototype$8.cross = function() { var aggr = this, curr = aggr.value, dims = aggr._dnames, vals = dims.map(function() { return {}; }), n = dims.length; // collect all group-by domain values function collect(cells) { var key$$1, i, t, v; for (key$$1 in cells) { t = cells[key$$1].tuple; for (i=0; i<n; ++i) { vals[i][(v = t[dims[i]])] = v; } } } collect(aggr._prev); collect(curr); // iterate over key cross-product, create cells as needed function generate(base, tuple, index) { var name = dims[index], v = vals[index++], k, key$$1; for (k in v) { tuple[name] = v[k]; key$$1 = base ? base + '|' + k : k; if (index < n) generate(key$$1, tuple, index); else if (!curr[key$$1]) aggr.cell(key$$1, tuple); } } generate('', {}, 0); }; prototype$8.init = function(_$$1) { // initialize input and output fields var inputs = (this._inputs = []), outputs = (this._outputs = []), inputMap = {}; function inputVisit(get) { var fields = array(accessorFields(get)), i = 0, n = fields.length, f; for (; i<n; ++i) { if (!inputMap[f=fields[i]]) { inputMap[f] = 1; inputs.push(f); } } } // initialize group-by dimensions this._dims = array(_$$1.groupby); this._dnames = this._dims.map(function(d) { var dname = accessorName(d); inputVisit(d); outputs.push(dname); return dname; }); this.cellkey = _$$1.key ? _$$1.key : groupkey(this._dims); // initialize aggregate measures this._countOnly = true; this._counts = []; this._measures = []; var fields = _$$1.fields || [null], ops = _$$1.ops || ['count'], as = _$$1.as || [], n = fields.length, map = {}, field$$1, op, m, mname, outname, i; if (n !== ops.length) { error$1('Unmatched number of fields and aggregate ops.'); } for (i=0; i<n; ++i) { field$$1 = fields[i]; op = ops[i]; if (field$$1 == null && op !== 'count') { error$1('Null aggregate field specified.'); } mname = accessorName(field$$1); outname = measureName(op, mname, as[i]); outputs.push(outname); if (op === 'count') { this._counts.push(outname); continue; } m = map[mname]; if (!m) { inputVisit(field$$1); m = (map[mname] = []); m.field = field$$1; this._measures.push(m); } if (op !== 'count') this._countOnly = false; m.push(createMeasure(op, outname)); } this._measures = this._measures.map(function(m) { return compileMeasures(m, m.field); }); return {}; // aggregation cells (this.value) }; // -- Cell Management ----- prototype$8.cellkey = groupkey(); prototype$8.cell = function(key$$1, t) { var cell = this.value[key$$1]; if (!cell) { cell = this.value[key$$1] = this.newcell(key$$1, t); this._adds[this._alen++] = cell; } else if (cell.num === 0 && this._drop && cell.stamp < this.stamp) { cell.stamp = this.stamp; this._adds[this._alen++] = cell; } else if (cell.stamp < this.stamp) { cell.stamp = this.stamp; this._mods[this._mlen++] = cell; } return cell; }; prototype$8.newcell = function(key$$1, t) { var cell = { key: key$$1, num: 0, agg: null, tuple: this.newtuple(t, this._prev && this._prev[key$$1]), stamp: this.stamp, store: false }; if (!this._countOnly) { var measures = this._measures, n = measures.length, i; cell.agg = Array(n); for (i=0; i<n; ++i) { cell.agg[i] = new measures[i](cell); } } if (cell.store) { cell.data = new TupleStore(); } return cell; }; prototype$8.newtuple = function(t, p) { var names = this._dnames, dims = this._dims, x = {}, i, n; for (i=0, n=dims.length; i<n; ++i) { x[names[i]] = dims[i](t); } return p ? replace(p.tuple, x) : ingest(x); }; // -- Process Tuples ----- prototype$8.add = function(t) { var key$$1 = this.cellkey(t), cell = this.cell(key$$1, t), agg, i, n; cell.num += 1; if (this._countOnly) return; if (cell.store) cell.data.add(t); agg = cell.agg; for (i=0, n=agg.length; i<n; ++i) { agg[i].add(agg[i].get(t), t); } }; prototype$8.rem = function(t) { var key$$1 = this.cellkey(t), cell = this.cell(key$$1, t), agg, i, n; cell.num -= 1; if (this._countOnly) return; if (cell.store) cell.data.rem(t); agg = cell.agg; for (i=0, n=agg.length; i<n; ++i) { agg[i].rem(agg[i].get(t), t); } }; prototype$8.celltuple = function(cell) { var tuple = cell.tuple, counts = this._counts, agg, i, n; // consolidate stored values if (cell.store) { cell.data.values(); } // update tuple properties for (i=0, n=counts.length; i<n; ++i) { tuple[counts[i]] = cell.num; } if (!this._countOnly) { agg = cell.agg; for (i=0, n=agg.length; i<n; ++i) { agg[i].set(tuple); } } return tuple; }; prototype$8.changes = function(out) { var adds = this._adds, mods = this._mods, prev = this._prev, drop = this._drop, add = out.add, rem = out.rem, mod = out.mod, cell, key$$1, i, n; if (prev) for (key$$1 in prev) { cell = prev[key$$1]; if (!drop || cell.num) rem.push(cell.tuple); } for (i=0, n=this._alen; i<n; ++i) { add.push(this.celltuple(adds[i])); adds[i] = null; // for garbage collection } for (i=0, n=this._mlen; i<n; ++i) { cell = mods[i]; (cell.num === 0 && drop ? rem : mod).push(this.celltuple(cell)); mods[i] = null; // for garbage collection } this._alen = this._mlen = 0; // reset list of active cells this._prev = null; return out; }; /** * Generates a binning function for discretizing data. * @constructor * @param {object} params - The parameters for this operator. The * provided values should be valid options for the {@link bin} function. * @param {function(object): *} params.field - The data field to bin. */ function Bin(params) { Transform.call(this, null, params); } Bin.Definition = { "type": "Bin", "metadata": {"modifies": true}, "params": [ { "name": "field", "type": "field", "required": true }, { "name": "anchor", "type": "number" }, { "name": "maxbins", "type": "number", "default": 20 }, { "name": "base", "type": "number", "default": 10 }, { "name": "divide", "type": "number", "array": true, "default": [5, 2] }, { "name": "extent", "type": "number", "array": true, "length": 2, "required": true }, { "name": "step", "type": "number" }, { "name": "steps", "type": "number", "array": true }, { "name": "minstep", "type": "number", "default": 0 }, { "name": "nice", "type": "boolean", "default": true }, { "name": "name", "type": "string" }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["bin0", "bin1"] } ] }; var prototype$10 = inherits(Bin, Transform); prototype$10.transform = function(_$$1, pulse) { var bins = this._bins(_$$1), start = bins.start, step = bins.step, as = _$$1.as || ['bin0', 'bin1'], b0 = as[0], b1 = as[1], flag; if (_$$1.modified()) { pulse = pulse.reflow(true); flag = pulse.SOURCE; } else { flag = pulse.modified(accessorFields(_$$1.field)) ? pulse.ADD_MOD : pulse.ADD; } pulse.visit(flag, function(t) { var v = bins(t); // minimum bin value (inclusive) t[b0] = v; // maximum bin value (exclusive) // use convoluted math for better floating point agreement // see https://github.com/vega/vega/issues/830 t[b1] = v == null ? null : start + step * (1 + (v - start) / step); }); return pulse.modifies(as); }; prototype$10._bins = function(_$$1) { if (this.value && !_$$1.modified()) { return this.value; } var field$$1 = _$$1.field, bins = bin(_$$1), start = bins.start, stop = bins.stop, step = bins.step, a, d; if ((a = _$$1.anchor) != null) { d = a - (start + step * Math.floor((a - start) / step)); start += d; stop += d; } var f = function(t) { var v = field$$1(t); if (v == null) { return null; } else { v = Math.max(start, Math.min(+v, stop - step)); return start + step * Math.floor((v - start) / step); } }; f.start = start; f.stop = stop; f.step = step; return this.value = accessor( f, accessorFields(field$$1), _$$1.name || 'bin_' + accessorName(field$$1) ); }; var SortedList = function(idFunc, source, input) { var $$$1 = idFunc, data = source || [], add = input || [], rem = {}, cnt = 0; return { add: function(t) { add.push(t); }, remove: function(t) { rem[$$$1(t)] = ++cnt; }, size: function() { return data.length; }, data: function(compare$$1, resort) { if (cnt) { data = data.filter(function(t) { return !rem[$$$1(t)]; }); rem = {}; cnt = 0; } if (resort && compare$$1) { data.sort(compare$$1); } if (add.length) { data = compare$$1 ? merge(compare$$1, data, add.sort(compare$$1)) : data.concat(add); add = []; } return data; } } }; /** * Collects all data tuples that pass through this operator. * @constructor * @param {object} params - The parameters for this operator. * @param {function(*,*): number} [params.sort] - An optional * comparator function for additionally sorting the collected tuples. */ function Collect(params) { Transform.call(this, [], params); } Collect.Definition = { "type": "Collect", "metadata": {"source": true}, "params": [ { "name": "sort", "type": "compare" } ] }; var prototype$11 = inherits(Collect, Transform); prototype$11.transform = function(_$$1, pulse) { var out = pulse.fork(pulse.ALL), list = SortedList(tupleid, this.value, out.materialize(out.ADD).add), sort = _$$1.sort, mod = pulse.changed() || (sort && (_$$1.modified('sort') || pulse.modified(sort.fields))); out.visit(out.REM, list.remove); this.modified(mod); this.value = out.source = list.data(sort, mod); return out; }; /** * Generates a comparator function. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<string>} params.fields - The fields to compare. * @param {Array<string>} [params.orders] - The sort orders. * Each entry should be one of "ascending" (default) or "descending". */ function Compare(params) { Operator.call(this, null, update$1, params); } inherits(Compare, Operator); function update$1(_$$1) { return (this.value && !_$$1.modified()) ? this.value : compare(_$$1.fields, _$$1.orders); } /** * Count regexp-defined pattern occurrences in a text field. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - An accessor for the text field. * @param {string} [params.pattern] - RegExp string defining the text pattern. * @param {string} [params.case] - One of 'lower', 'upper' or null (mixed) case. * @param {string} [params.stopwords] - RegExp string of words to ignore. */ function CountPattern(params) { Transform.call(this, null, params); } CountPattern.Definition = { "type": "CountPattern", "metadata": {"generates": true, "changes": true}, "params": [ { "name": "field", "type": "field", "required": true }, { "name": "case", "type": "enum", "values": ["upper", "lower", "mixed"], "default": "mixed" }, { "name": "pattern", "type": "string", "default": "[\\w\"]+" }, { "name": "stopwords", "type": "string", "default": "" }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["text", "count"] } ] }; function tokenize(text, tcase, match) { switch (tcase) { case 'upper': text = text.toUpperCase(); break; case 'lower': text = text.toLowerCase(); break; } return text.match(match); } var prototype$12 = inherits(CountPattern, Transform); prototype$12.transform = function(_$$1, pulse) { function process(update) { return function(tuple) { var tokens = tokenize(get(tuple), _$$1.case, match) || [], t; for (var i=0, n=tokens.length; i<n; ++i) { if (!stop.test(t = tokens[i])) update(t); } }; } var init = this._parameterCheck(_$$1, pulse), counts = this._counts, match = this._match, stop = this._stop, get = _$$1.field, as = _$$1.as || ['text', 'count'], add = process(function(t) { counts[t] = 1 + (counts[t] || 0); }), rem = process(function(t) { counts[t] -= 1; }); if (init) { pulse.visit(pulse.SOURCE, add); } else { pulse.visit(pulse.ADD, add); pulse.visit(pulse.REM, rem); } return this._finish(pulse, as); // generate output tuples }; prototype$12._parameterCheck = function(_$$1, pulse) { var init = false; if (_$$1.modified('stopwords') || !this._stop) { this._stop = new RegExp('^' + (_$$1.stopwords || '') + '$', 'i'); init = true; } if (_$$1.modified('pattern') || !this._match) { this._match = new RegExp((_$$1.pattern || '[\\w\']+'), 'g'); init = true; } if (_$$1.modified('field') || pulse.modified(_$$1.field.fields)) { init = true; } if (init) this._counts = {}; return init; }; prototype$12._finish = function(pulse, as) { var counts = this._counts, tuples = this._tuples || (this._tuples = {}), text = as[0], count = as[1], out = pulse.fork(), w, t, c; for (w in counts) { t = tuples[w]; c = counts[w] || 0; if (!t && c) { tuples[w] = (t = ingest({})); t[text] = w; t[count] = c; out.add.push(t); } else if (c === 0) { if (t) out.rem.push(t); counts[w] = null; tuples[w] = null; } else if (t[count] !== c) { t[count] = c; out.mod.push(t); } } return out.modifies(as); }; /** * Perform a cross-product of a tuple stream with itself. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object):boolean} [params.filter] - An optional filter * function for selectively including tuples in the cross product. * @param {Array<string>} [params.as] - The names of the output fields. */ function Cross(params) { Transform.call(this, null, params); } Cross.Definition = { "type": "Cross", "metadata": {"source": true, "generates": true, "changes": true}, "params": [ { "name": "filter", "type": "expr" }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["a", "b"] } ] }; var prototype$13 = inherits(Cross, Transform); prototype$13.transform = function(_$$1, pulse) { var out = pulse.fork(pulse.NO_SOURCE), data = this.value, as = _$$1.as || ['a', 'b'], a = as[0], b = as[1], reset = !data || pulse.changed(pulse.ADD_REM) || _$$1.modified('as') || _$$1.modified('filter'); if (reset) { if (data) out.rem = data; out.add = this.value = cross(pulse.source, a, b, _$$1.filter || truthy); } else { out.mod = data; } out.source = this.value; return out.modifies(as); }; function cross(input, a, b, filter) { var data = [], t = {}, n = input.length, i = 0, j, left; for (; i<n; ++i) { t[a] = left = input[i]; for (j=0; j<n; ++j) { t[b] = input[j]; if (filter(t)) { data.push(ingest(t)); t = {}; t[a] = left; } } } return data; } var Distributions = { kde: randomKDE, mixture: randomMixture, normal: randomNormal, uniform: randomUniform }; var DISTRIBUTIONS = 'distributions'; var FUNCTION = 'function'; var FIELD = 'field'; /** * Parse a parameter object for a probability distribution. * @param {object} def - The distribution parameter object. * @param {function():Array<object>} - A method for requesting * source data. Used for distributions (such as KDE) that * require sample data points. This method will only be * invoked if the 'from' parameter for a target data source * is not provided. Typically this method returns backing * source data for a Pulse object. * @return {object} - The output distribution object. */ function parse$1(def, data) { var func = def[FUNCTION]; if (!Distributions.hasOwnProperty(func)) { error$1('Unknown distribution function: ' + func); } var d = Distributions[func](); for (var name in def) { // if data field, extract values if (name === FIELD) { d.data((def.from || data()).map(def[name])); } // if distribution mixture, recurse to parse each definition else if (name === DISTRIBUTIONS) { d[name](def[name].map(function(_$$1) { return parse$1(_$$1, data); })); } // otherwise, simply set the parameter else if (typeof d[name] === FUNCTION) { d[name](def[name]); } } return d; } /** * Grid sample points for a probability density. Given a distribution and * a sampling extent, will generate points suitable for plotting either * PDF (probability density function) or CDF (cumulative distribution * function) curves. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.distribution - The probability distribution. This * is an object parameter dependent on the distribution type. * @param {string} [params.method='pdf'] - The distribution method to sample. * One of 'pdf' or 'cdf'. * @param {Array<number>} [params.extent] - The [min, max] extent over which * to sample the distribution. This argument is required in most cases, but * can be omitted if the distribution (e.g., 'kde') supports a 'data' method * that returns numerical sample points from which the extent can be deduced. * @param {number} [params.steps=100] - The number of sampling steps. */ function Density(params) { Transform.call(this, null, params); } var distributions = [ { "key": {"function": "normal"}, "params": [ { "name": "mean", "type": "number", "default": 0 }, { "name": "stdev", "type": "number", "default": 1 } ] }, { "key": {"function": "uniform"}, "params": [ { "name": "min", "type": "number", "default": 0 }, { "name": "max", "type": "number", "default": 1 } ] }, { "key": {"function": "kde"}, "params": [ { "name": "field", "type": "field", "required": true }, { "name": "from", "type": "data" }, { "name": "bandwidth", "type": "number", "default": 0 } ] } ]; var mixture = { "key": {"function": "mixture"}, "params": [ { "name": "distributions", "type": "param", "array": true, "params": distributions }, { "name": "weights", "type": "number", "array": true } ] }; Density.Definition = { "type": "Density", "metadata": {"generates": true, "source": true}, "params": [ { "name": "extent", "type": "number", "array": true, "length": 2 }, { "name": "steps", "type": "number", "default": 100 }, { "name": "method", "type": "string", "default": "pdf", "values": ["pdf", "cdf"] }, { "name": "distribution", "type": "param", "params": distributions.concat(mixture) }, { "name": "as", "type": "string", "array": true, "default": ["value", "density"] } ] }; var prototype$14 = inherits(Density, Transform); prototype$14.transform = function(_$$1, pulse) { var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); if (!this.value || pulse.changed() || _$$1.modified()) { var dist = parse$1(_$$1.distribution, source(pulse)), method = _$$1.method || 'pdf'; if (method !== 'pdf' && method !== 'cdf') { error$1('Invalid density method: ' + method); } if (!_$$1.extent && !dist.data) { error$1('Missing density extent parameter.'); } method = dist[method]; var as = _$$1.as || ['value', 'density'], domain = _$$1.extent || d3Array.extent(dist.data()), step = (domain[1] - domain[0]) / (_$$1.steps || 100), values = d3Array.range(domain[0], domain[1] + step/2, step) .map(function(v) { var tuple = {}; tuple[as[0]] = v; tuple[as[1]] = method(v); return ingest(tuple); }); if (this.value) out.rem = this.value; this.value = out.add = out.source = values; } return out; }; function source(pulse) { return function() { return pulse.materialize(pulse.SOURCE).source; }; } /** * Computes extents (min/max) for a data field. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The field over which to compute extends. */ function Extent(params) { Transform.call(this, [+Infinity, -Infinity], params); } Extent.Definition = { "type": "Extent", "metadata": {}, "params": [ { "name": "field", "type": "field", "required": true } ] }; var prototype$15 = inherits(Extent, Transform); prototype$15.transform = function(_$$1, pulse) { var extent$$1 = this.value, field$$1 = _$$1.field, min$$1 = extent$$1[0], max$$1 = extent$$1[1], flag = pulse.ADD, mod; mod = pulse.changed() || pulse.modified(field$$1.fields) || _$$1.modified('field'); if (mod) { flag = pulse.SOURCE; min$$1 = +Infinity; max$$1 = -Infinity; } pulse.visit(flag, function(t) { var v = field$$1(t); if (v != null) { if (v < min$$1) min$$1 = v; if (v > max$$1) max$$1 = v; } }); this.value = [min$$1, max$$1]; }; /** * Provides a bridge between a parent transform and a target subflow that * consumes only a subset of the tuples that pass through the parent. * @constructor * @param {Pulse} pulse - A pulse to use as the value of this operator. * @param {Transform} parent - The parent transform (typically a Facet instance). * @param {Transform} target - A transform that receives the subflow of tuples. */ function Subflow(pulse, parent) { Operator.call(this, pulse); this.parent = parent; } var prototype$17 = inherits(Subflow, Operator); prototype$17.connect = function(target) { this.targets().add(target); return (target.source = this); }; /** * Add an 'add' tuple to the subflow pulse. * @param {Tuple} t - The tuple being added. */ prototype$17.add = function(t) { this.value.add.push(t); }; /** * Add a 'rem' tuple to the subflow pulse. * @param {Tuple} t - The tuple being removed. */ prototype$17.rem = function(t) { this.value.rem.push(t); }; /** * Add a 'mod' tuple to the subflow pulse. * @param {Tuple} t - The tuple being modified. */ prototype$17.mod = function(t) { this.value.mod.push(t); }; /** * Re-initialize this operator's pulse value. * @param {Pulse} pulse - The pulse to copy from. * @see Pulse.init */ prototype$17.init = function(pulse) { this.value.init(pulse, pulse.NO_SOURCE); }; /** * Evaluate this operator. This method overrides the * default behavior to simply return the contained pulse value. * @return {Pulse} */ prototype$17.evaluate = function() { // assert: this.value.stamp === pulse.stamp return this.value; }; /** * Facets a dataflow into a set of subflows based on a key. * @constructor * @param {object} params - The parameters for this operator. * @param {function(Dataflow, string): Operator} params.subflow - A function * that generates a subflow of operators and returns its root operator. * @param {function(object): *} params.key - The key field to facet by. */ function Facet(params) { Transform.call(this, {}, params); this._keys = fastmap(); // cache previously calculated key values // keep track of active subflows, use as targets array for listeners // this allows us to limit propagation to only updated subflows var a = this._targets = []; a.active = 0; a.forEach = function(f) { for (var i=0, n=a.active; i<n; ++i) f(a[i], i, a); }; } var prototype$16 = inherits(Facet, Transform); prototype$16.activate = function(flow) { this._targets[this._targets.active++] = flow; }; prototype$16.subflow = function(key$$1, flow, pulse, parent) { var flows = this.value, sf = flows.hasOwnProperty(key$$1) && flows[key$$1], df, p; if (!sf) { p = parent || (p = this._group[key$$1]) && p.tuple; df = pulse.dataflow; sf = df.add(new Subflow(pulse.fork(pulse.NO_SOURCE), this)) .connect(flow(df, key$$1, p)); flows[key$$1] = sf; this.activate(sf); } else if (sf.value.stamp < pulse.stamp) { sf.init(pulse); this.activate(sf); } return sf; }; prototype$16.transform = function(_$$1, pulse) { var df = pulse.dataflow, self = this, key$$1 = _$$1.key, flow = _$$1.subflow, cache = this._keys, rekey = _$$1.modified('key'); function subflow(key$$1) { return self.subflow(key$$1, flow, pulse); } this._group = _$$1.group || {}; this._targets.active = 0; // reset list of active subflows pulse.visit(pulse.REM, function(t) { var id$$1 = tupleid(t), k = cache.get(id$$1); if (k !== undefined) { cache.delete(id$$1); subflow(k).rem(t); } }); pulse.visit(pulse.ADD, function(t) { var k = key$$1(t); cache.set(tupleid(t), k); subflow(k).add(t); }); if (rekey || pulse.modified(key$$1.fields)) { pulse.visit(pulse.MOD, function(t) { var id$$1 = tupleid(t), k0 = cache.get(id$$1), k1 = key$$1(t); if (k0 === k1) { subflow(k1).mod(t); } else { cache.set(id$$1, k1); subflow(k0).rem(t); subflow(k1).add(t); } }); } else if (pulse.changed(pulse.MOD)) { pulse.visit(pulse.MOD, function(t) { subflow(cache.get(tupleid(t))).mod(t); }); } if (rekey) { pulse.visit(pulse.REFLOW, function(t) { var id$$1 = tupleid(t), k0 = cache.get(id$$1), k1 = key$$1(t); if (k0 !== k1) { cache.set(id$$1, k1); subflow(k0).rem(t); subflow(k1).add(t); } }); } if (cache.empty > df.cleanThreshold) df.runAfter(cache.clean); return pulse; }; /** * Generates one or more field accessor functions. * If the 'name' parameter is an array, an array of field accessors * will be created and the 'as' parameter will be ignored. * @constructor * @param {object} params - The parameters for this operator. * @param {string} params.name - The field name(s) to access. * @param {string} params.as - The accessor function name. */ function Field(params) { Operator.call(this, null, update$2, params); } inherits(Field, Operator); function update$2(_$$1) { return (this.value && !_$$1.modified()) ? this.value : isArray(_$$1.name) ? array(_$$1.name).map(function(f) { return field(f); }) : field(_$$1.name, _$$1.as); } /** * Filters data tuples according to a predicate function. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.expr - The predicate expression function * that determines a tuple's filter status. Truthy values pass the filter. */ function Filter(params) { Transform.call(this, fastmap(), params); } Filter.Definition = { "type": "Filter", "metadata": {"changes": true}, "params": [ { "name": "expr", "type": "expr", "required": true } ] }; var prototype$18 = inherits(Filter, Transform); prototype$18.transform = function(_$$1, pulse) { var df = pulse.dataflow, cache = this.value, // cache ids of filtered tuples output = pulse.fork(), add = output.add, rem = output.rem, mod = output.mod, test = _$$1.expr, isMod = true; pulse.visit(pulse.REM, function(t) { var id$$1 = tupleid(t); if (!cache.has(id$$1)) rem.push(t); else cache.delete(id$$1); }); pulse.visit(pulse.ADD, function(t) { if (test(t, _$$1)) add.push(t); else cache.set(tupleid(t), 1); }); function revisit(t) { var id$$1 = tupleid(t), b = test(t, _$$1), s = cache.get(id$$1); if (b && s) { cache.delete(id$$1); add.push(t); } else if (!b && !s) { cache.set(id$$1, 1); rem.push(t); } else if (isMod && b && !s) { mod.push(t); } } pulse.visit(pulse.MOD, revisit); if (_$$1.modified()) { isMod = false; pulse.visit(pulse.REFLOW, revisit); } if (cache.empty > df.cleanThreshold) df.runAfter(cache.clean); return output; }; /** * Folds one more tuple fields into multiple tuples in which the field * name and values are available under new 'key' and 'value' fields. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.fields - An array of field accessors * for the tuple fields that should be folded. */ function Fold(params) { Transform.call(this, {}, params); } Fold.Definition = { "type": "Fold", "metadata": {"generates": true, "changes": true}, "params": [ { "name": "fields", "type": "field", "array": true, "required": true }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["key", "value"] } ] }; var prototype$19 = inherits(Fold, Transform); function keyFunction(f) { return f.fields.join('|'); } prototype$19.transform = function(_$$1, pulse) { var cache = this.value, reset = _$$1.modified('fields'), fields = _$$1.fields, as = _$$1.as || ['key', 'value'], key$$1 = as[0], value = as[1], keys = fields.map(keyFunction), n = fields.length, stamp = pulse.stamp, out = pulse.fork(pulse.NO_SOURCE), i = 0, mask = 0, id$$1; function add(t) { var f = (cache[tupleid(t)] = Array(n)); // create cache of folded tuples for (var i=0, ft; i<n; ++i) { // for each key, derive folds ft = (f[i] = derive(t)); ft[key$$1] = keys[i]; ft[value] = fields[i](t); out.add.push(ft); } } function mod(t) { var f = cache[tupleid(t)]; // get cache of folded tuples for (var i=0, ft; i<n; ++i) { // for each key, rederive folds if (!(mask & (1 << i))) continue; // field is unchanged ft = rederive(t, f[i], stamp); ft[key$$1] = keys[i]; ft[value] = fields[i](t); out.mod.push(ft); } } if (reset) { // on reset, remove all folded tuples and clear cache for (id$$1 in cache) out.rem.push.apply(out.rem, cache[id$$1]); cache = this.value = {}; pulse.visit(pulse.SOURCE, add); } else { pulse.visit(pulse.ADD, add); for (; i<n; ++i) { if (pulse.modified(fields[i].fields)) mask |= (1 << i); } if (mask) pulse.visit(pulse.MOD, mod); pulse.visit(pulse.REM, function(t) { var id$$1 = tupleid(t); out.rem.push.apply(out.rem, cache[id$$1]); cache[id$$1] = null; }); } return out.modifies(as); }; /** * Invokes a function for each data tuple and saves the results as a new field. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.expr - The formula function to invoke for each tuple. * @param {string} params.as - The field name under which to save the result. * @param {boolean} [params.initonly=false] - If true, the formula is applied to * added tuples only, and does not update in response to modifications. */ function Formula(params) { Transform.call(this, null, params); } Formula.Definition = { "type": "Formula", "metadata": {"modifies": true}, "params": [ { "name": "expr", "type": "expr", "required": true }, { "name": "as", "type": "string", "required": true }, { "name": "initonly", "type": "boolean" } ] }; var prototype$20 = inherits(Formula, Transform); prototype$20.transform = function(_$$1, pulse) { var func = _$$1.expr, as = _$$1.as, mod = _$$1.modified(), flag = _$$1.initonly ? pulse.ADD : mod ? pulse.SOURCE : pulse.modified(func.fields) ? pulse.ADD_MOD : pulse.ADD; function set(t) { t[as] = func(t, _$$1); } if (mod) { // parameters updated, need to reflow pulse = pulse.materialize().reflow(true); } if (!_$$1.initonly) { pulse.modifies(as); } return pulse.visit(flag, set); }; /** * Generates data tuples using a provided generator function. * @constructor * @param {object} params - The parameters for this operator. * @param {function(Parameters): object} params.generator - A tuple generator * function. This function is given the operator parameters as input. * Changes to any additional parameters will not trigger re-calculation * of previously generated tuples. Only future tuples are affected. * @param {number} params.size - The number of tuples to produce. */ function Generate(params) { Transform.call(this, [], params); } var prototype$21 = inherits(Generate, Transform); prototype$21.transform = function(_$$1, pulse) { var data = this.value, out = pulse.fork(pulse.ALL), num = _$$1.size - data.length, gen = _$$1.generator, add, rem, t; if (num > 0) { // need more tuples, generate and add for (add=[]; --num >= 0;) { add.push(t = ingest(gen(_$$1))); data.push(t); } out.add = out.add.length ? out.materialize(out.ADD).add.concat(add) : add; } else { // need fewer tuples, remove rem = data.slice(0, -num); out.rem = out.rem.length ? out.materialize(out.REM).rem.concat(rem) : rem; data = data.slice(-num); } out.source = this.value = data; return out; }; var Methods = { value: 'value', median: d3Array.median, mean: d3Array.mean, min: d3Array.min, max: d3Array.max }; var Empty = []; /** * Impute missing values. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to impute. * @param {Array<function(object): *>} [params.groupby] - An array of * accessors to determine series within which to perform imputation. * @param {function(object): *} params.key - An accessor for a key value. * Each key value should be unique within a group. New tuples will be * imputed for any key values that are not found within a group. * @param {Array<*>} [params.keyvals] - Optional array of required key * values. New tuples will be imputed for any key values that are not * found within a group. In addition, these values will be automatically * augmented with the key values observed in the input data. * @param {string} [method='value'] - The imputation method to use. One of * 'value', 'mean', 'median', 'max', 'min'. * @param {*} [value=0] - The constant value to use for imputation * when using method 'value'. */ function Impute(params) { Transform.call(this, [], params); } Impute.Definition = { "type": "Impute", "metadata": {"changes": true}, "params": [ { "name": "field", "type": "field", "required": true }, { "name": "key", "type": "field", "required": true }, { "name": "keyvals", "array": true }, { "name": "groupby", "type": "field", "array": true }, { "name": "method", "type": "enum", "default": "value", "values": ["value", "mean", "median", "max", "min"] }, { "name": "value", "default": 0 } ] }; var prototype$22 = inherits(Impute, Transform); function getValue(_$$1) { var m = _$$1.method || Methods.value, v; if (Methods[m] == null) { error$1('Unrecognized imputation method: ' + m); } else if (m === Methods.value) { v = _$$1.value !== undefined ? _$$1.value : 0; return function() { return v; }; } else { return Methods[m]; } } function getField(_$$1) { var f = _$$1.field; return function(t) { return t ? f(t) : NaN; }; } prototype$22.transform = function(_$$1, pulse) { var out = pulse.fork(pulse.ALL), impute = getValue(_$$1), field$$1 = getField(_$$1), fName = accessorName(_$$1.field), kName = accessorName(_$$1.key), gNames = (_$$1.groupby || []).map(accessorName), groups = partition$1(pulse.source, _$$1.groupby, _$$1.key, _$$1.keyvals), curr = [], prev = this.value, m = groups.domain.length, group, value, gVals, kVal, g, i, j, l, n, t; for (g=0, l=groups.length; g<l; ++g) { group = groups[g]; gVals = group.values; value = NaN; // add tuples for missing values for (j=0; j<m; ++j) { if (group[j] != null) continue; kVal = groups.domain[j]; t = {_impute: true}; for (i=0, n=gVals.length; i<n; ++i) t[gNames[i]] = gVals[i]; t[kName] = kVal; t[fName] = isNaN(value) ? (value = impute(group, field$$1)) : value; curr.push(ingest(t)); } } // update pulse with imputed tuples if (curr.length) out.add = out.materialize(out.ADD).add.concat(curr); if (prev.length) out.rem = out.materialize(out.REM).rem.concat(prev); this.value = curr; return out; }; function partition$1(data, groupby, key$$1, keyvals) { var get = function(f) { return f(t); }, groups = [], domain = keyvals ? keyvals.slice() : [], kMap = {}, gMap = {}, gVals, gKey, group, i, j, k, n, t; domain.forEach(function(k, i) { kMap[k] = i + 1; }); for (i=0, n=data.length; i<n; ++i) { t = data[i]; k = key$$1(t); j = kMap[k] || (kMap[k] = domain.push(k)); gKey = (gVals = groupby ? groupby.map(get) : Empty) + ''; if (!(group = gMap[gKey])) { group = (gMap[gKey] = []); groups.push(group); group.values = gVals; } group[j-1] = t; } groups.domain = domain; return groups; } /** * Extend input tuples with aggregate values. * Calcuates aggregate values and joins them with the input stream. * @constructor */ function JoinAggregate(params) { Aggregate.call(this, params); } JoinAggregate.Definition = { "type": "JoinAggregate", "metadata": {"modifies": true}, "params": [ { "name": "groupby", "type": "field", "array": true }, { "name": "fields", "type": "field", "null": true, "array": true }, { "name": "ops", "type": "enum", "array": true, "values": ValidAggregateOps }, { "name": "as", "type": "string", "null": true, "array": true }, { "name": "key", "type": "field" } ] }; var prototype$23 = inherits(JoinAggregate, Aggregate); prototype$23.transform = function(_$$1, pulse) { var aggr = this, mod = _$$1.modified(), cells; // process all input tuples to calculate aggregates if (aggr.value && (mod || pulse.modified(aggr._inputs))) { cells = aggr.value = mod ? aggr.init(_$$1) : {}; pulse.visit(pulse.SOURCE, function(t) { aggr.add(t); }); } else { cells = aggr.value = aggr.value || this.init(_$$1); pulse.visit(pulse.REM, function(t) { aggr.rem(t); }); pulse.visit(pulse.ADD, function(t) { aggr.add(t); }); } // update aggregation cells aggr.changes(); // write aggregate values to input tuples pulse.visit(pulse.SOURCE, function(t) { extend(t, cells[aggr.cellkey(t)].tuple); }); return pulse.reflow(mod).modifies(this._outputs); }; prototype$23.changes = function() { var adds = this._adds, mods = this._mods, i, n; for (i=0, n=this._alen; i<n; ++i) { this.celltuple(adds[i]); adds[i] = null; // for garbage collection } for (i=0, n=this._mlen; i<n; ++i) { this.celltuple(mods[i]); mods[i] = null; // for garbage collection } this._alen = this._mlen = 0; // reset list of active cells }; /** * Generates a key function. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<string>} params.fields - The field name(s) for the key function. * @param {boolean} params.flat - A boolean flag indicating if the field names * should be treated as flat property names, side-stepping nested field * lookups normally indicated by dot or bracket notation. */ function Key(params) { Operator.call(this, null, update$3, params); } inherits(Key, Operator); function update$3(_$$1) { return (this.value && !_$$1.modified()) ? this.value : key(_$$1.fields, _$$1.flat); } /** * Extend tuples by joining them with values from a lookup table. * @constructor * @param {object} params - The parameters for this operator. * @param {Map} params.index - The lookup table map. * @param {Array<function(object): *} params.fields - The fields to lookup. * @param {Array<string>} params.as - Output field names for each lookup value. * @param {*} [params.default] - A default value to use if lookup fails. */ function Lookup(params) { Transform.call(this, {}, params); } Lookup.Definition = { "type": "Lookup", "metadata": {"modifies": true}, "params": [ { "name": "index", "type": "index", "params": [ {"name": "from", "type": "data", "required": true }, {"name": "key", "type": "field", "required": true } ] }, { "name": "values", "type": "field", "array": true }, { "name": "fields", "type": "field", "array": true, "required": true }, { "name": "as", "type": "string", "array": true }, { "name": "default", "default": null } ] }; var prototype$24 = inherits(Lookup, Transform); prototype$24.transform = function(_$$1, pulse) { var out = pulse, as = _$$1.as, keys = _$$1.fields, index = _$$1.index, values = _$$1.values, defaultValue = _$$1.default==null ? null : _$$1.default, reset = _$$1.modified(), flag = reset ? pulse.SOURCE : pulse.ADD, n = keys.length, set, m, mods; if (values) { m = values.length; if (n > 1 && !as) { error$1('Multi-field lookup requires explicit "as" parameter.'); } if (as && as.length !== n * m) { error$1('The "as" parameter has too few output field names.'); } as = as || values.map(accessorName); set = function(t) { for (var i=0, k=0, j, v; i<n; ++i) { v = index.get(keys[i](t)); if (v == null) for (j=0; j<m; ++j, ++k) t[as[k]] = defaultValue; else for (j=0; j<m; ++j, ++k) t[as[k]] = values[j](v); } }; } else { if (!as) { error$1('Missing output field names.'); } set = function(t) { for (var i=0, v; i<n; ++i) { v = index.get(keys[i](t)); t[as[i]] = v==null ? defaultValue : v; } }; } if (reset) { out = pulse.reflow(true); } else { mods = keys.some(function(k) { return pulse.modified(k.fields); }); flag |= (mods ? pulse.MOD : 0); } pulse.visit(flag, set); return out.modifies(as); }; /** * Computes global min/max extents over a collection of extents. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<Array<number>>} params.extents - The input extents. */ function MultiExtent(params) { Operator.call(this, null, update$4, params); } inherits(MultiExtent, Operator); function update$4(_$$1) { if (this.value && !_$$1.modified()) { return this.value; } var min$$1 = +Infinity, max$$1 = -Infinity, ext = _$$1.extents, i, n, e; for (i=0, n=ext.length; i<n; ++i) { e = ext[i]; if (e[0] < min$$1) min$$1 = e[0]; if (e[1] > max$$1) max$$1 = e[1]; } return [min$$1, max$$1]; } /** * Merge a collection of value arrays. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<Array<*>>} params.values - The input value arrrays. */ function MultiValues(params) { Operator.call(this, null, update$5, params); } inherits(MultiValues, Operator); function update$5(_$$1) { return (this.value && !_$$1.modified()) ? this.value : _$$1.values.reduce(function(data, _$$1) { return data.concat(_$$1); }, []); } /** * Operator whose value is simply its parameter hash. This operator is * useful for enabling reactive updates to values of nested objects. * @constructor * @param {object} params - The parameters for this operator. */ function Params(params) { Transform.call(this, null, params); } inherits(Params, Transform); Params.prototype.transform = function(_$$1, pulse) { this.modified(_$$1.modified()); this.value = _$$1; return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); // do not pass tuples }; /** * Partitions pre-faceted data into tuple subflows. * @constructor * @param {object} params - The parameters for this operator. * @param {function(Dataflow, string): Operator} params.subflow - A function * that generates a subflow of operators and returns its root operator. * @param {function(object): Array<object>} params.field - The field * accessor for an array of subflow tuple objects. */ function PreFacet(params) { Facet.call(this, params); } var prototype$25 = inherits(PreFacet, Facet); prototype$25.transform = function(_$$1, pulse) { var self = this, flow = _$$1.subflow, field$$1 = _$$1.field; if (_$$1.modified('field') || field$$1 && pulse.modified(accessorFields(field$$1))) { error$1('PreFacet does not support field modification.'); } this._targets.active = 0; // reset list of active subflows pulse.visit(pulse.MOD, function(t) { var sf = self.subflow(tupleid(t), flow, pulse, t); field$$1 ? field$$1(t).forEach(function(_$$1) { sf.mod(_$$1); }) : sf.mod(t); }); pulse.visit(pulse.ADD, function(t) { var sf = self.subflow(tupleid(t), flow, pulse, t); field$$1 ? field$$1(t).forEach(function(_$$1) { sf.add(ingest(_$$1)); }) : sf.add(t); }); pulse.visit(pulse.REM, function(t) { var sf = self.subflow(tupleid(t), flow, pulse, t); field$$1 ? field$$1(t).forEach(function(_$$1) { sf.rem(_$$1); }) : sf.rem(t); }); return pulse; }; /** * Performs a relational projection, copying selected fields from source * tuples to a new set of derived tuples. * @param {object} params - The parameters for this operator. * @param {Array<function(object): *} params.fields - The fields to project, * as an array of field accessors. If unspecified, all fields will be * copied with names unchanged. * @param {Array<string>} params.as - Output field names for each projected * field. Any unspecified fields will use the field name provided by * the field accessor. * @constructor */ function Project(params) { Transform.call(this, null, params); } Project.Definition = { "type": "Project", "metadata": {"generates": true, "changes": true, "modifies": true}, "params": [ { "name": "fields", "type": "field", "array": true }, { "name": "as", "type": "string", "null": true, "array": true }, ] }; var prototype$26 = inherits(Project, Transform); prototype$26.transform = function(_$$1, pulse) { var fields = _$$1.fields, as = output(_$$1.fields, _$$1.as || []), derive$$1 = fields ? function(s, t) { return project(s, t, fields, as); } : rederive, out, lut; if (this.value) { lut = this.value; } else { pulse = pulse.addAll(); lut = this.value = {}; } out = pulse.fork(); pulse.visit(pulse.REM, function(t) { var id$$1 = tupleid(t); out.rem.push(lut[id$$1]); lut[id$$1] = null; }); pulse.visit(pulse.ADD, function(t) { var dt = derive$$1(t, ingest({})); lut[tupleid(t)] = dt; out.add.push(dt); }); pulse.visit(pulse.MOD, function(t) { out.mod.push(derive$$1(t, lut[tupleid(t)])); }); return out; }; function output(fields, as) { if (!fields) return null; return fields.map(function(f, i) { return as[i] || accessorName(f); }); } function project(s, t, fields, as) { for (var i=0, n=fields.length; i<n; ++i) { t[as[i]] = fields[i](s); } return t; } /** * Proxy the value of another operator as a pure signal value. * Ensures no tuples are propagated. * @constructor * @param {object} params - The parameters for this operator. * @param {*} params.value - The value to proxy, becomes the value of this operator. */ function Proxy(params) { Transform.call(this, null, params); } var prototype$27 = inherits(Proxy, Transform); prototype$27.transform = function(_$$1, pulse) { this.value = _$$1.value; return _$$1.modified('value') ? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS) : pulse.StopPropagation; }; /** * Relays a data stream between data processing pipelines. * If the derive parameter is set, this transform will create derived * copies of observed tuples. This provides derived data streams in which * modifications to the tuples do not pollute an upstream data source. * @param {object} params - The parameters for this operator. * @param {number} [params.derive=false] - Boolean flag indicating if * the transform should make derived copies of incoming tuples. * @constructor */ function Relay(params) { Transform.call(this, null, params); } var prototype$28 = inherits(Relay, Transform); prototype$28.transform = function(_$$1, pulse) { var out, lut; if (this.value) { lut = this.value; } else { out = pulse = pulse.addAll(); lut = this.value = {}; } if (_$$1.derive) { out = pulse.fork(); pulse.visit(pulse.REM, function(t) { var id$$1 = tupleid(t); out.rem.push(lut[id$$1]); lut[id$$1] = null; }); pulse.visit(pulse.ADD, function(t) { var dt = derive(t); lut[tupleid(t)] = dt; out.add.push(dt); }); pulse.visit(pulse.MOD, function(t) { out.mod.push(rederive(t, lut[tupleid(t)])); }); } return out; }; /** * Samples tuples passing through this operator. * Uses reservoir sampling to maintain a representative sample. * @constructor * @param {object} params - The parameters for this operator. * @param {number} [params.size=1000] - The maximum number of samples. */ function Sample(params) { Transform.call(this, [], params); this.count = 0; } Sample.Definition = { "type": "Sample", "metadata": {"source": true, "changes": true}, "params": [ { "name": "size", "type": "number", "default": 1000 } ] }; var prototype$29 = inherits(Sample, Transform); prototype$29.transform = function(_$$1, pulse) { var out = pulse.fork(), mod = _$$1.modified('size'), num = _$$1.size, res = this.value, cnt = this.count, cap = 0, map = res.reduce(function(m, t) { m[tupleid(t)] = 1; return m; }, {}); // sample reservoir update function function update(t) { var p, idx; if (res.length < num) { res.push(t); } else { idx = ~~((cnt + 1) * exports.random()); if (idx < res.length && idx >= cap) { p = res[idx]; if (map[tupleid(p)]) out.rem.push(p); // eviction res[idx] = t; } } ++cnt; } if (pulse.rem.length) { // find all tuples that should be removed, add to output pulse.visit(pulse.REM, function(t) { var id$$1 = tupleid(t); if (map[id$$1]) { map[id$$1] = -1; out.rem.push(t); } --cnt; }); // filter removed tuples out of the sample reservoir res = res.filter(function(t) { return map[tupleid(t)] !== -1; }); } if ((pulse.rem.length || mod) && res.length < num && pulse.source) { // replenish sample if backing data source is available cap = cnt = res.length; pulse.visit(pulse.SOURCE, function(t) { // update, but skip previously sampled tuples if (!map[tupleid(t)]) update(t); }); cap = -1; } if (mod && res.length > num) { for (var i=0, n=res.length-num; i<n; ++i) { map[tupleid(res[i])] = -1; out.rem.push(res[i]); } res = res.slice(n); } if (pulse.mod.length) { // propagate modified tuples in the sample reservoir pulse.visit(pulse.MOD, function(t) { if (map[tupleid(t)]) out.mod.push(t); }); } if (pulse.add.length) { // update sample reservoir pulse.visit(pulse.ADD, update); } if (pulse.add.length || cap < 0) { // output newly added tuples out.add = res.filter(function(t) { return !map[tupleid(t)]; }); } this.count = cnt; this.value = out.source = res; return out; }; /** * Generates data tuples for a specified sequence range of numbers. * @constructor * @param {object} params - The parameters for this operator. * @param {number} params.start - The first number in the sequence. * @param {number} params.stop - The last number (exclusive) in the sequence. * @param {number} [params.step=1] - The step size between numbers in the sequence. */ function Sequence(params) { Transform.call(this, null, params); } Sequence.Definition = { "type": "Sequence", "metadata": {"generates": true, "source": true}, "params": [ { "name": "start", "type": "number", "required": true }, { "name": "stop", "type": "number", "required": true }, { "name": "step", "type": "number", "default": 1 } ], "output": ["value"] }; var prototype$30 = inherits(Sequence, Transform); prototype$30.transform = function(_$$1, pulse) { if (this.value && !_$$1.modified()) return; var out = pulse.materialize().fork(pulse.MOD); out.rem = this.value ? pulse.rem.concat(this.value) : pulse.rem; out.source = this.value = d3Array.range(_$$1.start, _$$1.stop, _$$1.step || 1).map(ingest); out.add = pulse.add.concat(this.value); return out; }; /** * Propagates a new pulse without any tuples so long as the input * pulse contains some added, removed or modified tuples. * @param {object} params - The parameters for this operator. * @constructor */ function Sieve(params) { Transform.call(this, null, params); this.modified(true); // always treat as modified } var prototype$31 = inherits(Sieve, Transform); prototype$31.transform = function(_$$1, pulse) { this.value = pulse.source; return pulse.changed() ? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS) : pulse.StopPropagation; }; /** * An index that maps from unique, string-coerced, field values to tuples. * Assumes that the field serves as a unique key with no duplicate values. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The field accessor to index. */ function TupleIndex(params) { Transform.call(this, fastmap(), params); } var prototype$32 = inherits(TupleIndex, Transform); prototype$32.transform = function(_$$1, pulse) { var df = pulse.dataflow, field$$1 = _$$1.field, index = this.value, mod = true; function set(t) { index.set(field$$1(t), t); } if (_$$1.modified('field') || pulse.modified(field$$1.fields)) { index.clear(); pulse.visit(pulse.SOURCE, set); } else if (pulse.changed()) { pulse.visit(pulse.REM, function(t) { index.delete(field$$1(t)); }); pulse.visit(pulse.ADD, set); } else { mod = false; } this.modified(mod); if (index.empty > df.cleanThreshold) df.runAfter(index.clean); return pulse.fork(); }; /** * Extracts an array of values. Assumes the source data has already been * reduced as needed (e.g., by an upstream Aggregate transform). * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The domain field to extract. * @param {function(*,*): number} [params.sort] - An optional * comparator function for sorting the values. The comparator will be * applied to backing tuples prior to value extraction. */ function Values(params) { Transform.call(this, null, params); } var prototype$33 = inherits(Values, Transform); prototype$33.transform = function(_$$1, pulse) { var run = !this.value || _$$1.modified('field') || _$$1.modified('sort') || pulse.changed() || (_$$1.sort && pulse.modified(_$$1.sort.fields)); if (run) { this.value = (_$$1.sort ? pulse.source.slice().sort(_$$1.sort) : pulse.source).map(_$$1.field); } }; function WindowOp(op, field$$1, param, as) { var fn = WindowOps[op](field$$1, param); return { init: fn.init || zero, update: function(w, t) { t[as] = fn.next(w); } }; } var WindowOps = { row_number: function() { return { next: function(w) { return w.index + 1; } }; }, rank: function() { var rank; return { init: function() { rank = 1; }, next: function(w) { var i = w.index, data = w.data; return (i && w.compare(data[i - 1], data[i])) ? (rank = i + 1) : rank; } }; }, dense_rank: function() { var drank; return { init: function() { drank = 1; }, next: function(w) { var i = w.index, d = w.data; return (i && w.compare(d[i - 1], d[i])) ? ++drank : drank; } }; }, percent_rank: function() { var rank = WindowOps.rank(), next = rank.next; return { init: rank.init, next: function(w) { return (next(w) - 1) / (w.data.length - 1); } }; }, cume_dist: function() { var cume; return { init: function() { cume = 0; }, next: function(w) { var i = w.index, d = w.data, c = w.compare; if (cume < i) { while (i + 1 < d.length && !c(d[i], d[i + 1])) ++i; cume = i; } return (1 + cume) / d.length; } }; }, ntile: function(field$$1, num) { num = +num; if (!(num > 0)) error$1('ntile num must be greater than zero.'); var cume = WindowOps.cume_dist(), next = cume.next; return { init: cume.init, next: function(w) { return Math.ceil(num * next(w)); } }; }, lag: function(field$$1, offset) { offset = +offset || 1; return { next: function(w) { var i = w.index - offset; return i >= 0 ? field$$1(w.data[i]) : null; } }; }, lead: function(field$$1, offset) { offset = +offset || 1; return { next: function(w) { var i = w.index + offset, d = w.data; return i < d.length ? field$$1(d[i]) : null; } }; }, first_value: function(field$$1) { return { next: function(w) { return field$$1(w.data[w.i0]); } }; }, last_value: function(field$$1) { return { next: function(w) { return field$$1(w.data[w.i1 - 1]); } } }, nth_value: function(field$$1, nth) { nth = +nth; if (!(nth > 0)) error$1('nth_value nth must be greater than zero.'); return { next: function(w) { var i = w.i0 + (nth - 1); return i < w.i1 ? field$$1(w.data[i]) : null; } } } }; var ValidWindowOps = Object.keys(WindowOps); function WindowState(_$$1) { var self = this, ops = array(_$$1.ops), fields = array(_$$1.fields), params = array(_$$1.params), as = array(_$$1.as), outputs = self.outputs = [], windows = self.windows = [], inputs = {}, map = {}, countOnly = true, counts = [], measures = []; function visitInputs(f) { array(accessorFields(f)).forEach(function(_$$1) { inputs[_$$1] = 1; }); } visitInputs(_$$1.sort); ops.forEach(function(op, i) { var field$$1 = fields[i], mname = accessorName(field$$1), name = measureName(op, mname, as[i]); visitInputs(field$$1); outputs.push(name); // Window operation if (WindowOps.hasOwnProperty(op)) { windows.push(WindowOp(op, fields[i], params[i], name)); } // Aggregate operation else { if (field$$1 == null && op !== 'count') { error$1('Null aggregate field specified.'); } if (op === 'count') { counts.push(name); return; } countOnly = false; var m = map[mname]; if (!m) { m = (map[mname] = []); m.field = field$$1; measures.push(m); } m.push(createMeasure(op, name)); } }); if (counts.length || measures.length) { self.cell = cell(measures, counts, countOnly); } self.inputs = Object.keys(inputs); } var prototype$35 = WindowState.prototype; prototype$35.init = function() { this.windows.forEach(function(_$$1) { _$$1.init(); }); if (this.cell) this.cell.init(); }; prototype$35.update = function(w, t) { var self = this, cell = self.cell, wind = self.windows, data = w.data, m = wind && wind.length, j; if (cell) { for (j=w.p0; j<w.i0; ++j) cell.rem(data[j]); for (j=w.p1; j<w.i1; ++j) cell.add(data[j]); cell.set(t); } for (j=0; j<m; ++j) wind[j].update(w, t); }; function cell(measures, counts, countOnly) { measures = measures.map(function(m) { return compileMeasures(m, m.field); }); var cell = { num: 0, agg: null, store: false, count: counts }; if (!countOnly) { var n = measures.length, a = cell.agg = Array(n), i = 0; for (; i<n; ++i) a[i] = new measures[i](cell); } if (cell.store) { var store = cell.data = new TupleStore(); } cell.add = function(t) { cell.num += 1; if (countOnly) return; if (store) store.add(t); for (var i=0; i<n; ++i) { a[i].add(a[i].get(t), t); } }; cell.rem = function(t) { cell.num -= 1; if (countOnly) return; if (store) store.rem(t); for (var i=0; i<n; ++i) { a[i].rem(a[i].get(t), t); } }; cell.set = function(t) { var i, n; // consolidate stored values if (store) store.values(); // update tuple properties for (i=0, n=counts.length; i<n; ++i) t[counts[i]] = cell.num; if (!countOnly) for (i=0, n=a.length; i<n; ++i) a[i].set(t); }; cell.init = function() { cell.num = 0; if (store) store.reset(); for (var i=0; i<n; ++i) a[i].init(); }; return cell; } /** * Perform window calculations and write results to the input stream. * @constructor * @param {object} params - The parameters for this operator. * @param {function(*,*): number} [params.sort] - A comparator function for sorting tuples within a window. * @param {Array<function(object): *>} [params.groupby] - An array of accessors by which to partition tuples into separate windows. * @param {Array<string>} params.ops - An array of strings indicating window operations to perform. * @param {Array<function(object): *>} [params.fields] - An array of accessors * for data fields to use as inputs to window operations. * @param {Array<*>} [params.params] - An array of parameter values for window operations. * @param {Array<string>} [params.as] - An array of output field names for window operations. * @param {Array<number>} [params.frame] - Window frame definition as two-element array. * @param {boolean} [params.ignorePeers=false] - If true, base window frame boundaries on row * number alone, ignoring peers with identical sort values. If false (default), * the window boundaries will be adjusted to include peer values. */ function Window(params) { Transform.call(this, {}, params); this._mlen = 0; this._mods = []; } Window.Definition = { "type": "Window", "metadata": {"modifies": true}, "params": [ { "name": "sort", "type": "compare" }, { "name": "groupby", "type": "field", "array": true }, { "name": "ops", "type": "enum", "array": true, "values": ValidWindowOps.concat(ValidAggregateOps) }, { "name": "params", "type": "number", "null": true, "array": true }, { "name": "fields", "type": "field", "null": true, "array": true }, { "name": "as", "type": "string", "null": true, "array": true }, { "name": "frame", "type": "number", "null": true, "array": true, "length": 2, "default": [null, 0] }, { "name": "ignorePeers", "type": "boolean", "default": false } ] }; var prototype$34 = inherits(Window, Transform); prototype$34.transform = function(_$$1, pulse) { var self = this, state = self.state, mod = _$$1.modified(), i, n; this.stamp = pulse.stamp; // initialize window state if (!state || mod) { state = self.state = new WindowState(_$$1); } // retrieve group for a tuple var key$$1 = groupkey(_$$1.groupby); function group(t) { return self.group(key$$1(t)); } // partition input tuples if (mod || pulse.modified(state.inputs)) { self.value = {}; pulse.visit(pulse.SOURCE, function(t) { group(t).add(t); }); } else { pulse.visit(pulse.REM, function(t) { group(t).remove(t); }); pulse.visit(pulse.ADD, function(t) { group(t).add(t); }); } // perform window calculations for each modified partition for (i=0, n=self._mlen; i<n; ++i) { processPartition(self._mods[i], state, _$$1); } self._mlen = 0; self._mods = []; // TODO don't reflow everything? return pulse.reflow(mod).modifies(state.outputs); }; prototype$34.group = function(key$$1) { var self = this, group = self.value[key$$1]; if (!group) { group = self.value[key$$1] = SortedList(tupleid); group.stamp = -1; } if (group.stamp < self.stamp) { group.stamp = self.stamp; self._mods[self._mlen++] = group; } return group; }; function processPartition(list, state, _$$1) { var sort = _$$1.sort, range$$1 = sort && !_$$1.ignorePeers, frame = _$$1.frame || [null, 0], data = list.data(sort), n = data.length, i = 0, b = range$$1 ? d3Array.bisector(sort) : null, w = { i0: 0, i1: 0, p0: 0, p1: 0, index: 0, data: data, compare: sort || constant(-1) }; for (state.init(); i<n; ++i) { setWindow(w, frame, i, n); if (range$$1) adjustRange(w, b); state.update(w, data[i]); } } function setWindow(w, f, i, n) { w.p0 = w.i0; w.p1 = w.i1; w.i0 = f[0] == null ? 0 : Math.max(0, i - Math.abs(f[0])); w.i1 = f[1] == null ? n : Math.min(n, i + Math.abs(f[1]) + 1); w.index = i; } // if frame type is 'range', adjust window for peer values function adjustRange(w, bisect$$1) { var r0 = w.i0, r1 = w.i1 - 1, c = w.compare, d = w.data, n = d.length - 1; if (r0 > 0 && !c(d[r0], d[r0-1])) w.i0 = bisect$$1.left(d, d[r0]); if (r1 < n && !c(d[r1], d[r1+1])) w.i1 = bisect$$1.right(d, d[r1]); } var tx = Object.freeze({ aggregate: Aggregate, bin: Bin, collect: Collect, compare: Compare, countpattern: CountPattern, cross: Cross, density: Density, extent: Extent, facet: Facet, field: Field, filter: Filter, fold: Fold, formula: Formula, generate: Generate, impute: Impute, joinaggregate: JoinAggregate, key: Key, lookup: Lookup, multiextent: MultiExtent, multivalues: MultiValues, params: Params, prefacet: PreFacet, project: Project, proxy: Proxy, relay: Relay, sample: Sample, sequence: Sequence, sieve: Sieve, subflow: Subflow, tupleindex: TupleIndex, values: Values, window: Window }); function Bounds(b) { this.clear(); if (b) this.union(b); } var prototype$37 = Bounds.prototype; prototype$37.clone = function() { return new Bounds(this); }; prototype$37.clear = function() { this.x1 = +Number.MAX_VALUE; this.y1 = +Number.MAX_VALUE; this.x2 = -Number.MAX_VALUE; this.y2 = -Number.MAX_VALUE; return this; }; prototype$37.empty = function() { return ( this.x1 === +Number.MAX_VALUE && this.y1 === +Number.MAX_VALUE && this.x2 === -Number.MAX_VALUE && this.y2 === -Number.MAX_VALUE ); }; prototype$37.set = function(x1, y1, x2, y2) { if (x2 < x1) { this.x2 = x1; this.x1 = x2; } else { this.x1 = x1; this.x2 = x2; } if (y2 < y1) { this.y2 = y1; this.y1 = y2; } else { this.y1 = y1; this.y2 = y2; } return this; }; prototype$37.add = function(x, y) { if (x < this.x1) this.x1 = x; if (y < this.y1) this.y1 = y; if (x > this.x2) this.x2 = x; if (y > this.y2) this.y2 = y; return this; }; prototype$37.expand = function(d) { this.x1 -= d; this.y1 -= d; this.x2 += d; this.y2 += d; return this; }; prototype$37.round = function() { this.x1 = Math.floor(this.x1); this.y1 = Math.floor(this.y1); this.x2 = Math.ceil(this.x2); this.y2 = Math.ceil(this.y2); return this; }; prototype$37.translate = function(dx, dy) { this.x1 += dx; this.x2 += dx; this.y1 += dy; this.y2 += dy; return this; }; prototype$37.rotate = function(angle, x, y) { var cos = Math.cos(angle), sin = Math.sin(angle), cx = x - x*cos + y*sin, cy = y - x*sin - y*cos, x1 = this.x1, x2 = this.x2, y1 = this.y1, y2 = this.y2; return this.clear() .add(cos*x1 - sin*y1 + cx, sin*x1 + cos*y1 + cy) .add(cos*x1 - sin*y2 + cx, sin*x1 + cos*y2 + cy) .add(cos*x2 - sin*y1 + cx, sin*x2 + cos*y1 + cy) .add(cos*x2 - sin*y2 + cx, sin*x2 + cos*y2 + cy); }; prototype$37.union = function(b) { if (b.x1 < this.x1) this.x1 = b.x1; if (b.y1 < this.y1) this.y1 = b.y1; if (b.x2 > this.x2) this.x2 = b.x2; if (b.y2 > this.y2) this.y2 = b.y2; return this; }; prototype$37.intersect = function(b) { if (b.x1 > this.x1) this.x1 = b.x1; if (b.y1 > this.y1) this.y1 = b.y1; if (b.x2 < this.x2) this.x2 = b.x2; if (b.y2 < this.y2) this.y2 = b.y2; return this; }; prototype$37.encloses = function(b) { return b && ( this.x1 <= b.x1 && this.x2 >= b.x2 && this.y1 <= b.y1 && this.y2 >= b.y2 ); }; prototype$37.alignsWith = function(b) { return b && ( this.x1 == b.x1 || this.x2 == b.x2 || this.y1 == b.y1 || this.y2 == b.y2 ); }; prototype$37.intersects = function(b) { return b && !( this.x2 < b.x1 || this.x1 > b.x2 || this.y2 < b.y1 || this.y1 > b.y2 ); }; prototype$37.contains = function(x, y) { return !( x < this.x1 || x > this.x2 || y < this.y1 || y > this.y2 ); }; prototype$37.width = function() { return this.x2 - this.x1; }; prototype$37.height = function() { return this.y2 - this.y1; }; var gradient_id = 0; var Gradient = function(p0, p1) { var stops = [], gradient; return gradient = { id: 'gradient_' + (gradient_id++), x1: p0 ? p0[0] : 0, y1: p0 ? p0[1] : 0, x2: p1 ? p1[0] : 1, y2: p1 ? p1[1] : 0, stops: stops, stop: function(offset, color) { stops.push({offset: offset, color: color}); return gradient; } }; }; function Item(mark) { this.mark = mark; this.bounds = (this.bounds || new Bounds()); } function GroupItem(mark) { Item.call(this, mark); this.items = (this.items || []); } inherits(GroupItem, Item); // create a new DOM element function domCreate(doc, tag, ns) { if (!doc && typeof document !== 'undefined' && document.createElement) { doc = document; } return doc ? (ns ? doc.createElementNS(ns, tag) : doc.createElement(tag)) : null; } // find first child element with matching tag function domFind(el, tag) { tag = tag.toLowerCase(); var nodes = el.childNodes, i = 0, n = nodes.length; for (; i<n; ++i) if (nodes[i].tagName.toLowerCase() === tag) { return nodes[i]; } } // retrieve child element at given index // create & insert if doesn't exist or if tags do not match function domChild(el, index, tag, ns) { var a = el.childNodes[index], b; if (!a || a.tagName.toLowerCase() !== tag.toLowerCase()) { b = a || null; a = domCreate(el.ownerDocument, tag, ns); el.insertBefore(a, b); } return a; } // remove all child elements at or above the given index function domClear(el, index) { var nodes = el.childNodes, curr = nodes.length; while (curr > index) el.removeChild(nodes[--curr]); return el; } // generate css class name for mark function cssClass(mark) { return 'mark-' + mark.marktype + (mark.role ? ' role-' + mark.role : '') + (mark.name ? ' ' + mark.name : ''); } var Canvas; try { // try to load canvas module Canvas = require('canvas'); } catch (e) { try { // if canvas fails, try to load canvas-prebuilt Canvas = require('canvas-prebuilt'); } catch (e2) { // if all options fail, set to null Canvas = null; } } var Canvas$1 = function(w, h) { var canvas = domCreate(null, 'canvas'); if (canvas && canvas.getContext) { canvas.width = w; canvas.height = h; } else if (Canvas) { try { canvas = new Canvas(w, h); } catch (e) { canvas = null; } } return canvas; }; var Image$1 = typeof Image !== 'undefined' ? Image : (Canvas && Canvas.Image || null); function ResourceLoader(customLoader) { this._pending = 0; this._loader = customLoader || loader(); } var prototype$38 = ResourceLoader.prototype; prototype$38.pending = function() { return this._pending; }; function increment(loader$$1) { loader$$1._pending += 1; } function decrement(loader$$1) { loader$$1._pending -= 1; } prototype$38.sanitizeURL = function(uri) { var loader$$1 = this; increment(loader$$1); return loader$$1._loader.sanitize(uri, {context:'href'}) .then(function(opt) { decrement(loader$$1); return opt; }) .catch(function() { decrement(loader$$1); return null; }); }; prototype$38.loadImage = function(uri) { var loader$$1 = this; increment(loader$$1); return loader$$1._loader .sanitize(uri, {context:'image'}) .then(function(opt) { var url = opt.href; if (!url || !Image$1) throw {url: url}; var image = new Image$1(); image.onload = function() { decrement(loader$$1); image.loaded = true; }; image.onerror = function() { decrement(loader$$1); image.loaded = false; }; image.src = url; return image; }) .catch(function(e) { decrement(loader$$1); return {loaded: false, width: 0, height: 0, src: e && e.url || ''}; }); }; prototype$38.ready = function() { var loader$$1 = this; return new Promise(function(accept) { function poll(value) { if (!loader$$1.pending()) accept(value); else setTimeout(function() { poll(true); }, 10); } poll(false); }); }; var lookup = { 'basis': { curve: d3Shape.curveBasis }, 'basis-closed': { curve: d3Shape.curveBasisClosed }, 'basis-open': { curve: d3Shape.curveBasisOpen }, 'bundle': { curve: d3Shape.curveBundle, tension: 'beta', value: 0.85 }, 'cardinal': { curve: d3Shape.curveCardinal, tension: 'tension', value: 0 }, 'cardinal-open': { curve: d3Shape.curveCardinalOpen, tension: 'tension', value: 0 }, 'cardinal-closed': { curve: d3Shape.curveCardinalClosed, tension: 'tension', value: 0 }, 'catmull-rom': { curve: d3Shape.curveCatmullRom, tension: 'alpha', value: 0.5 }, 'catmull-rom-closed': { curve: d3Shape.curveCatmullRomClosed, tension: 'alpha', value: 0.5 }, 'catmull-rom-open': { curve: d3Shape.curveCatmullRomOpen, tension: 'alpha', value: 0.5 }, 'linear': { curve: d3Shape.curveLinear }, 'linear-closed': { curve: d3Shape.curveLinearClosed }, 'monotone': { horizontal: d3Shape.curveMonotoneY, vertical: d3Shape.curveMonotoneX }, 'natural': { curve: d3Shape.curveNatural }, 'step': { curve: d3Shape.curveStep }, 'step-after': { curve: d3Shape.curveStepAfter }, 'step-before': { curve: d3Shape.curveStepBefore } }; function curves(type, orientation, tension) { var entry = lookup.hasOwnProperty(type) && lookup[type], curve = null; if (entry) { curve = entry.curve || entry[orientation || 'vertical']; if (entry.tension && tension != null) { curve = curve[entry.tension](tension); } } return curve; } // Path parsing and rendering code adapted from fabric.js -- Thanks! var cmdlen = { m:2, l:2, h:1, v:1, c:6, s:4, q:4, t:2, a:7 }; var regexp = [/([MLHVCSQTAZmlhvcsqtaz])/g, /###/, /(\d)([-+])/g, /\s|,|###/]; var pathParse = function(pathstr) { var result = [], path$$1, curr, chunks, parsed, param, cmd, len, i, j, n, m; // First, break path into command sequence path$$1 = pathstr .slice() .replace(regexp[0], '###$1') .split(regexp[1]) .slice(1); // Next, parse each command in turn for (i=0, n=path$$1.length; i<n; ++i) { curr = path$$1[i]; chunks = curr .slice(1) .trim() .replace(regexp[2],'$1###$2') .split(regexp[3]); cmd = curr.charAt(0); parsed = [cmd]; for (j=0, m=chunks.length; j<m; ++j) { if ((param = +chunks[j]) === param) { // not NaN parsed.push(param); } } len = cmdlen[cmd.toLowerCase()]; if (parsed.length-1 > len) { for (j=1, m=parsed.length; j<m; j+=len) { result.push([cmd].concat(parsed.slice(j, j+len))); } } else { result.push(parsed); } } return result; }; var segmentCache = {}; var bezierCache = {}; var join = [].join; // Copied from Inkscape svgtopdf, thanks! function segments(x, y, rx, ry, large, sweep, rotateX, ox, oy) { var key = join.call(arguments); if (segmentCache[key]) { return segmentCache[key]; } var th = rotateX * (Math.PI/180); var sin_th = Math.sin(th); var cos_th = Math.cos(th); rx = Math.abs(rx); ry = Math.abs(ry); var px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5; var py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5; var pl = (px*px) / (rx*rx) + (py*py) / (ry*ry); if (pl > 1) { pl = Math.sqrt(pl); rx *= pl; ry *= pl; } var a00 = cos_th / rx; var a01 = sin_th / rx; var a10 = (-sin_th) / ry; var a11 = (cos_th) / ry; var x0 = a00 * ox + a01 * oy; var y0 = a10 * ox + a11 * oy; var x1 = a00 * x + a01 * y; var y1 = a10 * x + a11 * y; var d = (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0); var sfactor_sq = 1 / d - 0.25; if (sfactor_sq < 0) sfactor_sq = 0; var sfactor = Math.sqrt(sfactor_sq); if (sweep == large) sfactor = -sfactor; var xc = 0.5 * (x0 + x1) - sfactor * (y1-y0); var yc = 0.5 * (y0 + y1) + sfactor * (x1-x0); var th0 = Math.atan2(y0-yc, x0-xc); var th1 = Math.atan2(y1-yc, x1-xc); var th_arc = th1-th0; if (th_arc < 0 && sweep === 1){ th_arc += 2 * Math.PI; } else if (th_arc > 0 && sweep === 0) { th_arc -= 2 * Math.PI; } var segs = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001))); var result = []; for (var i=0; i<segs; ++i) { var th2 = th0 + i * th_arc / segs; var th3 = th0 + (i+1) * th_arc / segs; result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th]; } return (segmentCache[key] = result); } function bezier(params) { var key = join.call(params); if (bezierCache[key]) { return bezierCache[key]; } var cx = params[0], cy = params[1], th0 = params[2], th1 = params[3], rx = params[4], ry = params[5], sin_th = params[6], cos_th = params[7]; var a00 = cos_th * rx; var a01 = -sin_th * ry; var a10 = sin_th * rx; var a11 = cos_th * ry; var cos_th0 = Math.cos(th0); var sin_th0 = Math.sin(th0); var cos_th1 = Math.cos(th1); var sin_th1 = Math.sin(th1); var th_half = 0.5 * (th1 - th0); var sin_th_h2 = Math.sin(th_half * 0.5); var t = (8/3) * sin_th_h2 * sin_th_h2 / Math.sin(th_half); var x1 = cx + cos_th0 - t * sin_th0; var y1 = cy + sin_th0 + t * cos_th0; var x3 = cx + cos_th1; var y3 = cy + sin_th1; var x2 = x3 + t * sin_th1; var y2 = y3 - t * cos_th1; return (bezierCache[key] = [ a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3 ]); } var temp$1 = ['l', 0, 0, 0, 0, 0, 0, 0]; function scale(current, s) { var c = (temp$1[0] = current[0]); if (c === 'a' || c === 'A') { temp$1[1] = s * current[1]; temp$1[2] = s * current[2]; temp$1[6] = s * current[6]; temp$1[7] = s * current[7]; } else { for (var i=1, n=current.length; i<n; ++i) { temp$1[i] = s * current[i]; } } return temp$1; } var pathRender = function(context, path$$1, l, t, s) { var current, // current instruction previous = null, x = 0, // current x y = 0, // current y controlX = 0, // current control point x controlY = 0, // current control point y tempX, tempY, tempControlX, tempControlY; if (l == null) l = 0; if (t == null) t = 0; if (s == null) s = 1; if (context.beginPath) context.beginPath(); for (var i=0, len=path$$1.length; i<len; ++i) { current = path$$1[i]; if (s !== 1) current = scale(current, s); switch (current[0]) { // first letter case 'l': // lineto, relative x += current[1]; y += current[2]; context.lineTo(x + l, y + t); break; case 'L': // lineto, absolute x = current[1]; y = current[2]; context.lineTo(x + l, y + t); break; case 'h': // horizontal lineto, relative x += current[1]; context.lineTo(x + l, y + t); break; case 'H': // horizontal lineto, absolute x = current[1]; context.lineTo(x + l, y + t); break; case 'v': // vertical lineto, relative y += current[1]; context.lineTo(x + l, y + t); break; case 'V': // verical lineto, absolute y = current[1]; context.lineTo(x + l, y + t); break; case 'm': // moveTo, relative x += current[1]; y += current[2]; context.moveTo(x + l, y + t); break; case 'M': // moveTo, absolute x = current[1]; y = current[2]; context.moveTo(x + l, y + t); break; case 'c': // bezierCurveTo, relative tempX = x + current[5]; tempY = y + current[6]; controlX = x + current[3]; controlY = y + current[4]; context.bezierCurveTo( x + current[1] + l, // x1 y + current[2] + t, // y1 controlX + l, // x2 controlY + t, // y2 tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'C': // bezierCurveTo, absolute x = current[5]; y = current[6]; controlX = current[3]; controlY = current[4]; context.bezierCurveTo( current[1] + l, current[2] + t, controlX + l, controlY + t, x + l, y + t ); break; case 's': // shorthand cubic bezierCurveTo, relative // transform to absolute x,y tempX = x + current[3]; tempY = y + current[4]; // calculate reflection of previous control points controlX = 2 * x - controlX; controlY = 2 * y - controlY; context.bezierCurveTo( controlX + l, controlY + t, x + current[1] + l, y + current[2] + t, tempX + l, tempY + t ); // set control point to 2nd one of this command // the first control point is assumed to be the reflection of // the second control point on the previous command relative // to the current point. controlX = x + current[1]; controlY = y + current[2]; x = tempX; y = tempY; break; case 'S': // shorthand cubic bezierCurveTo, absolute tempX = current[3]; tempY = current[4]; // calculate reflection of previous control points controlX = 2*x - controlX; controlY = 2*y - controlY; context.bezierCurveTo( controlX + l, controlY + t, current[1] + l, current[2] + t, tempX + l, tempY + t ); x = tempX; y = tempY; // set control point to 2nd one of this command // the first control point is assumed to be the reflection of // the second control point on the previous command relative // to the current point. controlX = current[1]; controlY = current[2]; break; case 'q': // quadraticCurveTo, relative // transform to absolute x,y tempX = x + current[3]; tempY = y + current[4]; controlX = x + current[1]; controlY = y + current[2]; context.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'Q': // quadraticCurveTo, absolute tempX = current[3]; tempY = current[4]; context.quadraticCurveTo( current[1] + l, current[2] + t, tempX + l, tempY + t ); x = tempX; y = tempY; controlX = current[1]; controlY = current[2]; break; case 't': // shorthand quadraticCurveTo, relative // transform to absolute x,y tempX = x + current[1]; tempY = y + current[2]; if (previous[0].match(/[QqTt]/) === null) { // If there is no previous command or if the previous command was not a Q, q, T or t, // assume the control point is coincident with the current point controlX = x; controlY = y; } else if (previous[0] === 't') { // calculate reflection of previous control points for t controlX = 2 * x - tempControlX; controlY = 2 * y - tempControlY; } else if (previous[0] === 'q') { // calculate reflection of previous control points for q controlX = 2 * x - controlX; controlY = 2 * y - controlY; } tempControlX = controlX; tempControlY = controlY; context.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; controlX = x + current[1]; controlY = y + current[2]; break; case 'T': tempX = current[1]; tempY = current[2]; // calculate reflection of previous control points controlX = 2 * x - controlX; controlY = 2 * y - controlY; context.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'a': drawArc(context, x + l, y + t, [ current[1], current[2], current[3], current[4], current[5], current[6] + x + l, current[7] + y + t ]); x += current[6]; y += current[7]; break; case 'A': drawArc(context, x + l, y + t, [ current[1], current[2], current[3], current[4], current[5], current[6] + l, current[7] + t ]); x = current[6]; y = current[7]; break; case 'z': case 'Z': context.closePath(); break; } previous = current; } }; function drawArc(context, x, y, coords) { var seg = segments( coords[5], // end x coords[6], // end y coords[0], // radius x coords[1], // radius y coords[3], // large flag coords[4], // sweep flag coords[2], // rotation x, y ); for (var i=0; i<seg.length; ++i) { var bez = bezier(seg[i]); context.bezierCurveTo(bez[0], bez[1], bez[2], bez[3], bez[4], bez[5]); } } var tau = 2 * Math.PI; var halfSqrt3 = Math.sqrt(3) / 2; var builtins = { 'circle': { draw: function(context, size) { var r = Math.sqrt(size) / 2; context.moveTo(r, 0); context.arc(0, 0, r, 0, tau); } }, 'cross': { draw: function(context, size) { var r = Math.sqrt(size) / 2, s = r / 2.5; context.moveTo(-r, -s); context.lineTo(-r, s); context.lineTo(-s, s); context.lineTo(-s, r); context.lineTo(s, r); context.lineTo(s, s); context.lineTo(r, s); context.lineTo(r, -s); context.lineTo(s, -s); context.lineTo(s, -r); context.lineTo(-s, -r); context.lineTo(-s, -s); context.closePath(); } }, 'diamond': { draw: function(context, size) { var r = Math.sqrt(size) / 2; context.moveTo(-r, 0); context.lineTo(0, -r); context.lineTo(r, 0); context.lineTo(0, r); context.closePath(); } }, 'square': { draw: function(context, size) { var w = Math.sqrt(size), x = -w / 2; context.rect(x, x, w, w); } }, 'triangle-up': { draw: function(context, size) { var r = Math.sqrt(size) / 2, h = halfSqrt3 * r; context.moveTo(0, -h); context.lineTo(-r, h); context.lineTo(r, h); context.closePath(); } }, 'triangle-down': { draw: function(context, size) { var r = Math.sqrt(size) / 2, h = halfSqrt3 * r; context.moveTo(0, h); context.lineTo(-r, -h); context.lineTo(r, -h); context.closePath(); } }, 'triangle-right': { draw: function(context, size) { var r = Math.sqrt(size) / 2, h = halfSqrt3 * r; context.moveTo(h, 0); context.lineTo(-h, -r); context.lineTo(-h, r); context.closePath(); } }, 'triangle-left': { draw: function(context, size) { var r = Math.sqrt(size) / 2, h = halfSqrt3 * r; context.moveTo(-h, 0); context.lineTo(h, -r); context.lineTo(h, r); context.closePath(); } } }; function symbols(_$$1) { return builtins.hasOwnProperty(_$$1) ? builtins[_$$1] : customSymbol(_$$1); } var custom = {}; function customSymbol(path$$1) { if (!custom.hasOwnProperty(path$$1)) { var parsed = pathParse(path$$1); custom[path$$1] = { draw: function(context, size) { pathRender(context, parsed, 0, 0, Math.sqrt(size) / 2); } }; } return custom[path$$1]; } function rectangleX(d) { return d.x; } function rectangleY(d) { return d.y; } function rectangleWidth(d) { return d.width; } function rectangleHeight(d) { return d.height; } function constant$1(_$$1) { return function() { return _$$1; }; } var vg_rect = function() { var x = rectangleX, y = rectangleY, width = rectangleWidth, height = rectangleHeight, cornerRadius = constant$1(0), context = null; function rectangle(_$$1, x0, y0) { var buffer, x1 = x0 != null ? x0 : +x.call(this, _$$1), y1 = y0 != null ? y0 : +y.call(this, _$$1), w = +width.call(this, _$$1), h = +height.call(this, _$$1), cr = +cornerRadius.call(this, _$$1); if (!context) context = buffer = d3Path.path(); if (cr <= 0) { context.rect(x1, y1, w, h); } else { var x2 = x1 + w, y2 = y1 + h; context.moveTo(x1 + cr, y1); context.lineTo(x2 - cr, y1); context.quadraticCurveTo(x2, y1, x2, y1 + cr); context.lineTo(x2, y2 - cr); context.quadraticCurveTo(x2, y2, x2 - cr, y2); context.lineTo(x1 + cr, y2); context.quadraticCurveTo(x1, y2, x1, y2 - cr); context.lineTo(x1, y1 + cr); context.quadraticCurveTo(x1, y1, x1 + cr, y1); context.closePath(); } if (buffer) { context = null; return buffer + '' || null; } } rectangle.x = function(_$$1) { if (arguments.length) { x = typeof _$$1 === 'function' ? _$$1 : constant$1(+_$$1); return rectangle; } else { return x; } }; rectangle.y = function(_$$1) { if (arguments.length) { y = typeof _$$1 === 'function' ? _$$1 : constant$1(+_$$1); return rectangle; } else { return y; } }; rectangle.width = function(_$$1) { if (arguments.length) { width = typeof _$$1 === 'function' ? _$$1 : constant$1(+_$$1); return rectangle; } else { return width; } }; rectangle.height = function(_$$1) { if (arguments.length) { height = typeof _$$1 === 'function' ? _$$1 : constant$1(+_$$1); return rectangle; } else { return height; } }; rectangle.cornerRadius = function(_$$1) { if (arguments.length) { cornerRadius = typeof _$$1 === 'function' ? _$$1 : constant$1(+_$$1); return rectangle; } else { return cornerRadius; } }; rectangle.context = function(_$$1) { if (arguments.length) { context = _$$1 == null ? null : _$$1; return rectangle; } else { return context; } }; return rectangle; }; var pi = Math.PI; var vg_trail = function() { var x, y, size, defined, context = null, ready, x1, y1, r1; function point(x2, y2, w2) { var r2 = w2 / 2; if (ready) { var ux = y1 - y2, uy = x2 - x1; if (ux || uy) { // get normal vector var ud = Math.sqrt(ux * ux + uy * uy), rx = (ux /= ud) * r1, ry = (uy /= ud) * r1, t = Math.atan2(uy, ux); // draw segment context.moveTo(x1 - rx, y1 - ry); context.lineTo(x2 - ux * r2, y2 - uy * r2); context.arc(x2, y2, r2, t - pi, t); context.lineTo(x1 + rx, y1 + ry); context.arc(x1, y1, r1, t, t + pi); } else { context.arc(x2, y2, r2, 0, 2*pi); } context.closePath(); } else { ready = 1; } x1 = x2; y1 = y2; r1 = r2; } function trail(data) { var i, n = data.length, d, defined0 = false, buffer; if (context == null) context = buffer = d3Path.path(); for (i = 0; i <= n; ++i) { if (!(i < n && defined(d = data[i], i, data)) === defined0) { if (defined0 = !defined0) ready = 0; } if (defined0) point(+x(d, i, data), +y(d, i, data), +size(d, i, data)); } if (buffer) { context = null; return buffer + '' || null; } } trail.x = function(_$$1) { if (arguments.length) { x = _$$1; return trail; } else { return x; } }; trail.y = function(_$$1) { if (arguments.length) { y = _$$1; return trail; } else { return y; } }; trail.size = function(_$$1) { if (arguments.length) { size = _$$1; return trail; } else { return size; } }; trail.defined = function(_$$1) { if (arguments.length) { defined = _$$1; return trail; } else { return defined; } }; trail.context = function(_$$1) { if (arguments.length) { if (_$$1 == null) { context = null; } else { context = _$$1; } return trail; } else { return context; } }; return trail; }; function x(item) { return item.x || 0; } function y(item) { return item.y || 0; } function w(item) { return item.width || 0; } function ts(item) { return item.size || 1; } function h(item) { return item.height || 0; } function xw(item) { return (item.x || 0) + (item.width || 0); } function yh(item) { return (item.y || 0) + (item.height || 0); } function sa(item) { return item.startAngle || 0; } function ea(item) { return item.endAngle || 0; } function pa(item) { return item.padAngle || 0; } function ir(item) { return item.innerRadius || 0; } function or(item) { return item.outerRadius || 0; } function cr(item) { return item.cornerRadius || 0; } function def(item) { return !(item.defined === false); } function size(item) { return item.size == null ? 64 : item.size; } function type(item) { return symbols(item.shape || 'circle'); } var arcShape = d3Shape.arc().startAngle(sa).endAngle(ea).padAngle(pa) .innerRadius(ir).outerRadius(or).cornerRadius(cr); var areavShape = d3Shape.area().x(x).y1(y).y0(yh).defined(def); var areahShape = d3Shape.area().y(y).x1(x).x0(xw).defined(def); var lineShape = d3Shape.line().x(x).y(y).defined(def); var rectShape = vg_rect().x(x).y(y).width(w).height(h).cornerRadius(cr); var symbolShape = d3Shape.symbol().type(type).size(size); var trailShape = vg_trail().x(x).y(y).defined(def).size(ts); function arc$2(context, item) { return arcShape.context(context)(item); } function area$1(context, items) { var item = items[0], interp = item.interpolate || 'linear'; return (item.orient === 'horizontal' ? areahShape : areavShape) .curve(curves(interp, item.orient, item.tension)) .context(context)(items); } function line$1(context, items) { var item = items[0], interp = item.interpolate || 'linear'; return lineShape.curve(curves(interp, item.orient, item.tension)) .context(context)(items); } function rectangle(context, item, x, y) { return rectShape.context(context)(item, x, y); } function shape(context, item) { return (item.mark.shape || item.shape) .context(context)(item); } function symbol$1(context, item) { return symbolShape.context(context)(item); } function trail(context, items) { return trailShape.context(context)(items); } var boundStroke = function(bounds, item) { if (item.stroke && item.opacity !== 0 && item.strokeOpacity !== 0) { bounds.expand(item.strokeWidth != null ? +item.strokeWidth : 1); } return bounds; }; var bounds; var tau$1 = Math.PI * 2; var halfPi = tau$1 / 4; var circleThreshold = tau$1 - 1e-8; function context(_$$1) { bounds = _$$1; return context; } function noop() {} function add$1(x, y) { bounds.add(x, y); } context.beginPath = noop; context.closePath = noop; context.moveTo = add$1; context.lineTo = add$1; context.rect = function(x, y, w, h) { add$1(x, y); add$1(x + w, y + h); }; context.quadraticCurveTo = function(x1, y1, x2, y2) { add$1(x1, y1); add$1(x2, y2); }; context.bezierCurveTo = function(x1, y1, x2, y2, x3, y3) { add$1(x1, y1); add$1(x2, y2); add$1(x3, y3); }; context.arc = function(cx, cy, r, sa, ea, ccw) { if (Math.abs(ea - sa) > circleThreshold) { add$1(cx - r, cy - r); add$1(cx + r, cy + r); return; } var xmin = Infinity, xmax = -Infinity, ymin = Infinity, ymax = -Infinity, s, i, x, y; function update(a) { x = r * Math.cos(a); y = r * Math.sin(a); if (x < xmin) xmin = x; if (x > xmax) xmax = x; if (y < ymin) ymin = y; if (y > ymax) ymax = y; } // Sample end points and interior points aligned with 90 degrees update(sa); update(ea); if (ea !== sa) { sa = sa % tau$1; if (sa < 0) sa += tau$1; ea = ea % tau$1; if (ea < 0) ea += tau$1; if (ea < sa) { ccw = !ccw; // flip direction s = sa; sa = ea; ea = s; // swap end-points } if (ccw) { ea -= tau$1; s = sa - (sa % halfPi); for (i=0; i<3 && s>ea; ++i, s-=halfPi) update(s); } else { s = sa - (sa % halfPi) + halfPi; for (i=0; i<3 && s<ea; ++i, s=s+halfPi) update(s); } } add$1(cx + xmin, cy + ymin); add$1(cx + xmax, cy + ymax); }; var gradient = function(context, gradient, bounds) { var w = bounds.width(), h = bounds.height(), x1 = bounds.x1 + gradient.x1 * w, y1 = bounds.y1 + gradient.y1 * h, x2 = bounds.x1 + gradient.x2 * w, y2 = bounds.y1 + gradient.y2 * h, stop = gradient.stops, i = 0, n = stop.length, linearGradient = context.createLinearGradient(x1, y1, x2, y2); for (; i<n; ++i) { linearGradient.addColorStop(stop[i].offset, stop[i].color); } return linearGradient; }; var color = function(context, item, value) { return (value.id) ? gradient(context, value, item.bounds) : value; }; var fill = function(context, item, opacity) { opacity *= (item.fillOpacity==null ? 1 : item.fillOpacity); if (opacity > 0) { context.globalAlpha = opacity; context.fillStyle = color(context, item, item.fill); return true; } else { return false; } }; var Empty$1 = []; var stroke = function(context, item, opacity) { var lw = (lw = item.strokeWidth) != null ? lw : 1; if (lw <= 0) return false; opacity *= (item.strokeOpacity==null ? 1 : item.strokeOpacity); if (opacity > 0) { context.globalAlpha = opacity; context.strokeStyle = color(context, item, item.stroke); context.lineWidth = lw; context.lineCap = item.strokeCap || 'butt'; context.lineJoin = item.strokeJoin || 'miter'; context.miterLimit = item.strokeMiterLimit || 10; if (context.setLineDash) { context.setLineDash(item.strokeDash || Empty$1); context.lineDashOffset = item.strokeDashOffset || 0; } return true; } else { return false; } }; function compare$1(a, b) { return a.zindex - b.zindex || a.index - b.index; } function zorder(scene) { if (!scene.zdirty) return scene.zitems; var items = scene.items, output = [], item, i, n; for (i=0, n=items.length; i<n; ++i) { item = items[i]; item.index = i; if (item.zindex) output.push(item); } scene.zdirty = false; return scene.zitems = output.sort(compare$1); } function visit(scene, visitor) { var items = scene.items, i, n; if (!items || !items.length) return; var zitems = zorder(scene); if (zitems && zitems.length) { for (i=0, n=items.length; i<n; ++i) { if (!items[i].zindex) visitor(items[i]); } items = zitems; } for (i=0, n=items.length; i<n; ++i) { visitor(items[i]); } } function pickVisit(scene, visitor) { var items = scene.items, hit, i; if (!items || !items.length) return null; var zitems = zorder(scene); if (zitems && zitems.length) items = zitems; for (i=items.length; --i >= 0;) { if (hit = visitor(items[i])) return hit; } if (items === zitems) { for (items=scene.items, i=items.length; --i >= 0;) { if (!items[i].zindex) { if (hit = visitor(items[i])) return hit; } } } return null; } function drawAll(path$$1) { return function(context, scene, bounds) { visit(scene, function(item) { if (!bounds || bounds.intersects(item.bounds)) { drawPath(path$$1, context, item, item); } }); }; } function drawOne(path$$1) { return function(context, scene, bounds) { if (scene.items.length && (!bounds || bounds.intersects(scene.bounds))) { drawPath(path$$1, context, scene.items[0], scene.items); } }; } function drawPath(path$$1, context, item, items) { var opacity = item.opacity == null ? 1 : item.opacity; if (opacity === 0) return; if (path$$1(context, items)) return; if (item.fill && fill(context, item, opacity)) { context.fill(); } if (item.stroke && stroke(context, item, opacity)) { context.stroke(); } } var trueFunc = function() { return true; }; function pick(test) { if (!test) test = trueFunc; return function(context, scene, x, y, gx, gy) { if (context.pixelRatio > 1) { x *= context.pixelRatio; y *= context.pixelRatio; } return pickVisit(scene, function(item) { var b = item.bounds; // first hit test against bounding box if ((b && !b.contains(gx, gy)) || !b) return; // if in bounding box, perform more careful test if (test(context, item, x, y, gx, gy)) return item; }); }; } function hitPath(path$$1, filled) { return function(context, o, x, y) { var item = Array.isArray(o) ? o[0] : o, fill = (filled == null) ? item.fill : filled, stroke = item.stroke && context.isPointInStroke, lw, lc; if (stroke) { lw = item.strokeWidth; lc = item.strokeCap; context.lineWidth = lw != null ? lw : 1; context.lineCap = lc != null ? lc : 'butt'; } return path$$1(context, o) ? false : (fill && context.isPointInPath(x, y)) || (stroke && context.isPointInStroke(x, y)); }; } function pickPath(path$$1) { return pick(hitPath(path$$1)); } var translate = function(x, y) { return 'translate(' + x + ',' + y + ')'; }; var translateItem = function(item) { return translate(item.x || 0, item.y || 0); }; var markItemPath = function(type, shape) { function attr(emit, item) { emit('transform', translateItem(item)); emit('d', shape(null, item)); } function bound(bounds, item) { shape(context(bounds), item); return boundStroke(bounds, item) .translate(item.x || 0, item.y || 0); } function draw(context$$1, item) { var x = item.x || 0, y = item.y || 0; context$$1.translate(x, y); context$$1.beginPath(); shape(context$$1, item); context$$1.translate(-x, -y); } return { type: type, tag: 'path', nested: false, attr: attr, bound: bound, draw: drawAll(draw), pick: pickPath(draw) }; }; var arc$1 = markItemPath('arc', arc$2); var markMultiItemPath = function(type, shape) { function attr(emit, item) { var items = item.mark.items; if (items.length) emit('d', shape(null, items)); } function bound(bounds, mark) { var items = mark.items; if (items.length === 0) { return bounds; } else { shape(context(bounds), items); return boundStroke(bounds, items[0]); } } function draw(context$$1, items) { context$$1.beginPath(); shape(context$$1, items); } var hit = hitPath(draw); function pick$$1(context$$1, scene, x, y, gx, gy) { var items = scene.items, b = scene.bounds; if (!items || !items.length || b && !b.contains(gx, gy)) { return null; } if (context$$1.pixelRatio > 1) { x *= context$$1.pixelRatio; y *= context$$1.pixelRatio; } return hit(context$$1, items, x, y) ? items[0] : null; } return { type: type, tag: 'path', nested: true, attr: attr, bound: bound, draw: drawOne(draw), pick: pick$$1 }; }; var area$2 = markMultiItemPath('area', area$1); var clip_id = 1; function resetSVGClipId() { clip_id = 1; } var clip = function(renderer, item, size) { var defs = renderer._defs, id = item.clip_id || (item.clip_id = 'clip' + clip_id++), c = defs.clipping[id] || (defs.clipping[id] = {id: id}); c.width = size.width || 0; c.height = size.height || 0; return 'url(#' + id + ')'; }; var StrokeOffset = 0.5; function attr(emit, item) { emit('transform', translateItem(item)); } function background(emit, item) { var offset = item.stroke ? StrokeOffset : 0; emit('class', 'background'); emit('d', rectangle(null, item, offset, offset)); } function foreground(emit, item, renderer) { var url = item.clip ? clip(renderer, item, item) : null; emit('clip-path', url); } function bound(bounds, group) { if (!group.clip && group.items) { var items = group.items; for (var j=0, m=items.length; j<m; ++j) { bounds.union(items[j].bounds); } } if (group.clip || group.width || group.height) { boundStroke( bounds.add(0, 0).add(group.width || 0, group.height || 0), group ); } return bounds.translate(group.x || 0, group.y || 0); } function draw(context, scene, bounds) { var renderer = this; visit(scene, function(group) { var gx = group.x || 0, gy = group.y || 0, w = group.width || 0, h = group.height || 0, offset, opacity; // setup graphics context context.save(); context.translate(gx, gy); // draw group background if (group.stroke || group.fill) { opacity = group.opacity == null ? 1 : group.opacity; if (opacity > 0) { context.beginPath(); offset = group.stroke ? StrokeOffset : 0; rectangle(context, group, offset, offset); if (group.fill && fill(context, group, opacity)) { context.fill(); } if (group.stroke && stroke(context, group, opacity)) { context.stroke(); } } } // set clip and bounds if (group.clip) { context.beginPath(); context.rect(0, 0, w, h); context.clip(); } if (bounds) bounds.translate(-gx, -gy); // draw group contents visit(group, function(item) { renderer.draw(context, item, bounds); }); // restore graphics context if (bounds) bounds.translate(gx, gy); context.restore(); }); } function pick$1(context, scene, x, y, gx, gy) { if (scene.bounds && !scene.bounds.contains(gx, gy) || !scene.items) { return null; } var handler = this; return pickVisit(scene, function(group) { var hit, dx, dy, b; // first hit test against bounding box // if a group is clipped, that should be handled by the bounds check. b = group.bounds; if (b && !b.contains(gx, gy)) return; // passed bounds check, so test sub-groups dx = (group.x || 0); dy = (group.y || 0); context.save(); context.translate(dx, dy); dx = gx - dx; dy = gy - dy; hit = pickVisit(group, function(mark) { return pickMark(mark, dx, dy) ? handler.pick(mark, x, y, dx, dy) : null; }); context.restore(); if (hit) return hit; hit = scene.interactive !== false && (group.fill || group.stroke) && dx >= 0 && dx <= group.width && dy >= 0 && dy <= group.height; return hit ? group : null; }); } function pickMark(mark, x, y) { return (mark.interactive !== false || mark.marktype === 'group') && mark.bounds && mark.bounds.contains(x, y); } var group = { type: 'group', tag: 'g', nested: false, attr: attr, bound: bound, draw: draw, pick: pick$1, background: background, foreground: foreground }; function getImage(item, renderer) { var image = item.image; if (!image || image.url !== item.url) { image = {loaded: false, width: 0, height: 0}; renderer.loadImage(item.url).then(function(image) { item.image = image; item.image.url = item.url; }); } return image; } function imageXOffset(align, w) { return align === 'center' ? w / 2 : align === 'right' ? w : 0; } function imageYOffset(baseline, h) { return baseline === 'middle' ? h / 2 : baseline === 'bottom' ? h : 0; } function attr$1(emit, item, renderer) { var image = getImage(item, renderer), x = item.x || 0, y = item.y || 0, w = (item.width != null ? item.width : image.width) || 0, h = (item.height != null ? item.height : image.height) || 0, a = item.aspect === false ? 'none' : 'xMidYMid'; x -= imageXOffset(item.align, w); y -= imageYOffset(item.baseline, h); emit('href', image.src || '', 'http://www.w3.org/1999/xlink', 'xlink:href'); emit('transform', translate(x, y)); emit('width', w); emit('height', h); emit('preserveAspectRatio', a); } function bound$1(bounds, item) { var image = item.image, x = item.x || 0, y = item.y || 0, w = (item.width != null ? item.width : (image && image.width)) || 0, h = (item.height != null ? item.height : (image && image.height)) || 0; x -= imageXOffset(item.align, w); y -= imageYOffset(item.baseline, h); return bounds.set(x, y, x + w, y + h); } function draw$1(context, scene, bounds) { var renderer = this; visit(scene, function(item) { if (bounds && !bounds.intersects(item.bounds)) return; // bounds check var image = getImage(item, renderer), x = item.x || 0, y = item.y || 0, w = (item.width != null ? item.width : image.width) || 0, h = (item.height != null ? item.height : image.height) || 0, opacity, ar0, ar1, t; x -= imageXOffset(item.align, w); y -= imageYOffset(item.baseline, h); if (item.aspect !== false) { ar0 = image.width / image.height; ar1 = item.width / item.height; if (ar0 === ar0 && ar1 === ar1 && ar0 !== ar1) { if (ar1 < ar0) { t = w / ar0; y += (h - t) / 2; h = t; } else { t = h * ar0; x += (w - t) / 2; w = t; } } } if (image.loaded) { context.globalAlpha = (opacity = item.opacity) != null ? opacity : 1; context.drawImage(image, x, y, w, h); } }); } var image = { type: 'image', tag: 'image', nested: false, attr: attr$1, bound: bound$1, draw: draw$1, pick: pick(), get: getImage, xOffset: imageXOffset, yOffset: imageYOffset }; var line$2 = markMultiItemPath('line', line$1); function attr$2(emit, item) { emit('transform', translateItem(item)); emit('d', item.path); } function path$1(context$$1, item) { var path$$1 = item.path; if (path$$1 == null) return true; var cache = item.pathCache; if (!cache || cache.path !== path$$1) { (item.pathCache = cache = pathParse(path$$1)).path = path$$1; } pathRender(context$$1, cache, item.x, item.y); } function bound$2(bounds, item) { return path$1(context(bounds), item) ? bounds.set(0, 0, 0, 0) : boundStroke(bounds, item); } var path$2 = { type: 'path', tag: 'path', nested: false, attr: attr$2, bound: bound$2, draw: drawAll(path$1), pick: pickPath(path$1) }; function attr$3(emit, item) { emit('d', rectangle(null, item)); } function bound$3(bounds, item) { var x, y; return boundStroke(bounds.set( x = item.x || 0, y = item.y || 0, (x + item.width) || 0, (y + item.height) || 0 ), item); } function draw$2(context, item) { context.beginPath(); rectangle(context, item); } var rect = { type: 'rect', tag: 'path', nested: false, attr: attr$3, bound: bound$3, draw: drawAll(draw$2), pick: pickPath(draw$2) }; function attr$4(emit, item) { emit('transform', translateItem(item)); emit('x2', item.x2 != null ? item.x2 - (item.x||0) : 0); emit('y2', item.y2 != null ? item.y2 - (item.y||0) : 0); } function bound$4(bounds, item) { var x1, y1; return boundStroke(bounds.set( x1 = item.x || 0, y1 = item.y || 0, item.x2 != null ? item.x2 : x1, item.y2 != null ? item.y2 : y1 ), item); } function path$3(context, item, opacity) { var x1, y1, x2, y2; if (item.stroke && stroke(context, item, opacity)) { x1 = item.x || 0; y1 = item.y || 0; x2 = item.x2 != null ? item.x2 : x1; y2 = item.y2 != null ? item.y2 : y1; context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); return true; } return false; } function draw$3(context, scene, bounds) { visit(scene, function(item) { if (bounds && !bounds.intersects(item.bounds)) return; // bounds check var opacity = item.opacity == null ? 1 : item.opacity; if (opacity && path$3(context, item, opacity)) { context.stroke(); } }); } function hit(context, item, x, y) { if (!context.isPointInStroke) return false; return path$3(context, item, 1) && context.isPointInStroke(x, y); } var rule = { type: 'rule', tag: 'line', nested: false, attr: attr$4, bound: bound$4, draw: draw$3, pick: pick(hit) }; var shape$1 = markItemPath('shape', shape); var symbol$2 = markItemPath('symbol', symbol$1); var context$1; var fontHeight; var textMetrics = { height: height, measureWidth: measureWidth, estimateWidth: estimateWidth, width: estimateWidth, canvas: canvas }; canvas(true); // make dumb, simple estimate if no canvas is available function estimateWidth(item) { fontHeight = height(item); return estimate(textValue(item)); } function estimate(text) { return ~~(0.8 * text.length * fontHeight); } // measure text width if canvas is available function measureWidth(item) { context$1.font = font(item); return measure$1(textValue(item)); } function measure$1(text) { return context$1.measureText(text).width; } function height(item) { return item.fontSize != null ? item.fontSize : 11; } function canvas(use) { context$1 = use && (context$1 = Canvas$1(1,1)) ? context$1.getContext('2d') : null; textMetrics.width = context$1 ? measureWidth : estimateWidth; } function textValue(item) { var s = item.text; if (s == null) { return ''; } else { return item.limit > 0 ? truncate$1(item) : s + ''; } } function truncate$1(item) { var limit = +item.limit, text = item.text + '', width; if (context$1) { context$1.font = font(item); width = measure$1; } else { fontHeight = height(item); width = estimate; } if (width(text) < limit) return text; var ellipsis = item.ellipsis || '\u2026', rtl = item.dir === 'rtl', lo = 0, hi = text.length, mid; limit -= width(ellipsis); if (rtl) { while (lo < hi) { mid = (lo + hi >>> 1); if (width(text.slice(mid)) > limit) lo = mid + 1; else hi = mid; } return ellipsis + text.slice(lo); } else { while (lo < hi) { mid = 1 + (lo + hi >>> 1); if (width(text.slice(0, mid)) < limit) lo = mid; else hi = mid - 1; } return text.slice(0, lo) + ellipsis; } } function font(item, quote) { var font = item.font; if (quote && font) { font = String(font).replace(/"/g, '\''); } return '' + (item.fontStyle ? item.fontStyle + ' ' : '') + (item.fontVariant ? item.fontVariant + ' ' : '') + (item.fontWeight ? item.fontWeight + ' ' : '') + height(item) + 'px ' + (font || 'sans-serif'); } function offset(item) { // perform our own font baseline calculation // why? not all browsers support SVG 1.1 'alignment-baseline' :( var baseline = item.baseline, h = height(item); return Math.round( baseline === 'top' ? 0.79*h : baseline === 'middle' ? 0.30*h : baseline === 'bottom' ? -0.21*h : 0 ); } var textAlign = { 'left': 'start', 'center': 'middle', 'right': 'end' }; var tempBounds = new Bounds(); function attr$5(emit, item) { var dx = item.dx || 0, dy = (item.dy || 0) + offset(item), x = item.x || 0, y = item.y || 0, a = item.angle || 0, r = item.radius || 0, t; if (r) { t = (item.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } emit('text-anchor', textAlign[item.align] || 'start'); if (a) { t = translate(x, y) + ' rotate('+a+')'; if (dx || dy) t += ' ' + translate(dx, dy); } else { t = translate(x + dx, y + dy); } emit('transform', t); } function bound$5(bounds, item, noRotate) { var h = textMetrics.height(item), a = item.align, r = item.radius || 0, x = item.x || 0, y = item.y || 0, dx = item.dx || 0, dy = (item.dy || 0) + offset(item) - Math.round(0.8*h), // use 4/5 offset w, t; if (r) { t = (item.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } // horizontal alignment w = textMetrics.width(item); if (a === 'center') { dx -= (w / 2); } else if (a === 'right') { dx -= w; } else { // left by default, do nothing } bounds.set(dx+=x, dy+=y, dx+w, dy+h); if (item.angle && !noRotate) { bounds.rotate(item.angle*Math.PI/180, x, y); } return bounds.expand(noRotate || !w ? 0 : 1); } function draw$4(context, scene, bounds) { visit(scene, function(item) { var opacity, x, y, r, t, str; if (bounds && !bounds.intersects(item.bounds)) return; // bounds check if (!(str = textValue(item))) return; // get text string opacity = item.opacity == null ? 1 : item.opacity; if (opacity === 0) return; context.font = font(item); context.textAlign = item.align || 'left'; x = item.x || 0; y = item.y || 0; if ((r = item.radius)) { t = (item.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } if (item.angle) { context.save(); context.translate(x, y); context.rotate(item.angle * Math.PI/180); x = y = 0; // reset x, y } x += (item.dx || 0); y += (item.dy || 0) + offset(item); if (item.fill && fill(context, item, opacity)) { context.fillText(str, x, y); } if (item.stroke && stroke(context, item, opacity)) { context.strokeText(str, x, y); } if (item.angle) context.restore(); }); } function hit$1(context, item, x, y, gx, gy) { if (item.fontSize <= 0) return false; if (!item.angle) return true; // bounds sufficient if no rotation // project point into space of unrotated bounds var b = bound$5(tempBounds, item, true), a = -item.angle * Math.PI / 180, cos = Math.cos(a), sin = Math.sin(a), ix = item.x, iy = item.y, px = cos*gx - sin*gy + (ix - ix*cos + iy*sin), py = sin*gx + cos*gy + (iy - ix*sin - iy*cos); return b.contains(px, py); } var text = { type: 'text', tag: 'text', nested: false, attr: attr$5, bound: bound$5, draw: draw$4, pick: pick(hit$1) }; var trail$1 = markMultiItemPath('trail', trail); var marks = { arc: arc$1, area: area$2, group: group, image: image, line: line$2, path: path$2, rect: rect, rule: rule, shape: shape$1, symbol: symbol$2, text: text, trail: trail$1 }; var boundItem$1 = function(item, func, opt) { var type = marks[item.mark.marktype], bound = func || type.bound; if (type.nested) item = item.mark; return bound(item.bounds || (item.bounds = new Bounds()), item, opt); }; var DUMMY = {mark: null}; var boundMark = function(mark, bounds, opt) { var type = marks[mark.marktype], bound = type.bound, items = mark.items, hasItems = items && items.length, i, n, item, b; if (type.nested) { if (hasItems) { item = items[0]; } else { // no items, fake it DUMMY.mark = mark; item = DUMMY; } b = boundItem$1(item, bound, opt); bounds = bounds && bounds.union(b) || b; return bounds; } bounds = bounds || mark.bounds && mark.bounds.clear() || new Bounds(); if (hasItems) { for (i=0, n=items.length; i<n; ++i) { bounds.union(boundItem$1(items[i], bound, opt)); } } return mark.bounds = bounds; }; var keys = [ 'marktype', 'name', 'role', 'interactive', 'clip', 'items', 'zindex', 'x', 'y', 'width', 'height', 'align', 'baseline', // layout 'fill', 'fillOpacity', 'opacity', // fill 'stroke', 'strokeOpacity', 'strokeWidth', 'strokeCap', // stroke 'strokeDash', 'strokeDashOffset', // stroke dash 'startAngle', 'endAngle', 'innerRadius', 'outerRadius', // arc 'cornerRadius', 'padAngle', // arc, rect 'interpolate', 'tension', 'orient', 'defined', // area, line 'url', // image 'path', // path 'x2', 'y2', // rule 'size', 'shape', // symbol 'text', 'angle', 'theta', 'radius', 'dx', 'dy', // text 'font', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariant' // font ]; function sceneToJSON(scene, indent) { return JSON.stringify(scene, keys, indent); } function sceneFromJSON(json) { var scene = (typeof json === 'string' ? JSON.parse(json) : json); return initialize(scene); } function initialize(scene) { var type = scene.marktype, items = scene.items, parent, i, n; if (items) { for (i=0, n=items.length; i<n; ++i) { parent = type ? 'mark' : 'group'; items[i][parent] = scene; if (items[i].zindex) items[i][parent].zdirty = true; if ('group' === (type || parent)) initialize(items[i]); } } if (type) boundMark(scene); return scene; } function Scenegraph(scene) { if (arguments.length) { this.root = sceneFromJSON(scene); } else { this.root = createMark({ marktype: 'group', name: 'root', role: 'frame' }); this.root.items = [new GroupItem(this.root)]; } } var prototype$39 = Scenegraph.prototype; prototype$39.toJSON = function(indent) { return sceneToJSON(this.root, indent || 0); }; prototype$39.mark = function(markdef, group, index) { group = group || this.root.items[0]; var mark = createMark(markdef, group); group.items[index] = mark; if (mark.zindex) mark.group.zdirty = true; return mark; }; function createMark(def, group) { return { bounds: new Bounds(), clip: !!def.clip, group: group, interactive: def.interactive === false ? false : true, items: [], marktype: def.marktype, name: def.name || undefined, role: def.role || undefined, zindex: def.zindex || 0 }; } function Handler(customLoader) { this._active = null; this._handlers = {}; this._loader = customLoader || loader(); } var prototype$40 = Handler.prototype; prototype$40.initialize = function(el, origin, obj) { this._el = el; this._obj = obj || null; return this.origin(origin); }; prototype$40.element = function() { return this._el; }; prototype$40.origin = function(origin) { this._origin = origin || [0, 0]; return this; }; prototype$40.scene = function(scene) { if (!arguments.length) return this._scene; this._scene = scene; return this; }; // add an event handler // subclasses should override prototype$40.on = function(/*type, handler*/) {}; // remove an event handler // subclasses should override prototype$40.off = function(/*type, handler*/) {}; // return an array with all registered event handlers prototype$40.handlers = function() { var h = this._handlers, a = [], k; for (k in h) { a.push.apply(a, h[k]); } return a; }; prototype$40.eventName = function(name) { var i = name.indexOf('.'); return i < 0 ? name : name.slice(0,i); }; prototype$40.handleHref = function(event, item, href) { this._loader .sanitize(href, {context:'href'}) .then(function(opt) { var e = new MouseEvent(event.type, event), a = domCreate(null, 'a'); for (var name in opt) a.setAttribute(name, opt[name]); a.dispatchEvent(e); }) .catch(function() { /* do nothing */ }); }; prototype$40.handleTooltip = function(event, item, tooltipText) { this._el.setAttribute('title', tooltipText || ''); }; /** * Create a new Renderer instance. * @param {object} [loader] - Optional loader instance for * image and href URL sanitization. If not specified, a * standard loader instance will be generated. * @constructor */ function Renderer(loader) { this._el = null; this._bgcolor = null; this._loader = new ResourceLoader(loader); } var prototype$41 = Renderer.prototype; /** * Initialize a new Renderer instance. * @param {DOMElement} el - The containing DOM element for the display. * @param {number} width - The coordinate width of the display, in pixels. * @param {number} height - The coordinate height of the display, in pixels. * @param {Array<number>} origin - The origin of the display, in pixels. * The coordinate system will be translated to this point. * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply * the width and height to determine the final pixel size. * @return {Renderer} - This renderer instance; */ prototype$41.initialize = function(el, width, height, origin, scaleFactor) { this._el = el; return this.resize(width, height, origin, scaleFactor); }; /** * Returns the parent container element for a visualization. * @return {DOMElement} - The containing DOM element. */ prototype$41.element = function() { return this._el; }; /** * Returns the scene element (e.g., canvas or SVG) of the visualization * Subclasses must override if the first child is not the scene element. * @return {DOMElement} - The scene (e.g., canvas or SVG) element. */ prototype$41.scene = function() { return this._el && this._el.firstChild; }; /** * Get / set the background color. */ prototype$41.background = function(bgcolor) { if (arguments.length === 0) return this._bgcolor; this._bgcolor = bgcolor; return this; }; /** * Resize the display. * @param {number} width - The new coordinate width of the display, in pixels. * @param {number} height - The new coordinate height of the display, in pixels. * @param {Array<number>} origin - The new origin of the display, in pixels. * The coordinate system will be translated to this point. * @param {number} [scaleFactor=1] - Optional scaleFactor by which to multiply * the width and height to determine the final pixel size. * @return {Renderer} - This renderer instance; */ prototype$41.resize = function(width, height, origin, scaleFactor) { this._width = width; this._height = height; this._origin = origin || [0, 0]; this._scale = scaleFactor || 1; return this; }; /** * Report a dirty item whose bounds should be redrawn. * This base class method does nothing. Subclasses that perform * incremental should implement this method. * @param {Item} item - The dirty item whose bounds should be redrawn. */ prototype$41.dirty = function(/*item*/) { }; /** * Render an input scenegraph, potentially with a set of dirty items. * This method will perform an immediate rendering with available resources. * The renderer may also need to perform image loading to perform a complete * render. This process can lead to asynchronous re-rendering of the scene * after this method returns. To receive notification when rendering is * complete, use the renderAsync method instead. * @param {object} scene - The root mark of a scenegraph to render. * @return {Renderer} - This renderer instance. */ prototype$41.render = function(scene) { var r = this; // bind arguments into a render call, and cache it // this function may be subsequently called for async redraw r._call = function() { r._render(scene); }; // invoke the renderer r._call(); // clear the cached call for garbage collection // async redraws will stash their own copy r._call = null; return r; }; /** * Internal rendering method. Renderer subclasses should override this * method to actually perform rendering. * @param {object} scene - The root mark of a scenegraph to render. */ prototype$41._render = function(/*scene*/) { // subclasses to override }; /** * Asynchronous rendering method. Similar to render, but returns a Promise * that resolves when all rendering is completed. Sometimes a renderer must * perform image loading to get a complete rendering. The returned * Promise will not resolve until this process completes. * @param {object} scene - The root mark of a scenegraph to render. * @return {Promise} - A Promise that resolves when rendering is complete. */ prototype$41.renderAsync = function(scene) { var r = this.render(scene); return this._ready ? this._ready.then(function() { return r; }) : Promise.resolve(r); }; /** * Internal method for asynchronous resource loading. * Proxies method calls to the ImageLoader, and tracks loading * progress to invoke a re-render once complete. * @param {string} method - The method name to invoke on the ImageLoader. * @param {string} uri - The URI for the requested resource. * @return {Promise} - A Promise that resolves to the requested resource. */ prototype$41._load = function(method, uri) { var r = this, p = r._loader[method](uri); if (!r._ready) { // re-render the scene when loading completes var call = r._call; r._ready = r._loader.ready() .then(function(redraw) { if (redraw) call(); r._ready = null; }); } return p; }; /** * Sanitize a URL to include as a hyperlink in the rendered scene. * This method proxies a call to ImageLoader.sanitizeURL, but also tracks * image loading progress and invokes a re-render once complete. * @param {string} uri - The URI string to sanitize. * @return {Promise} - A Promise that resolves to the sanitized URL. */ prototype$41.sanitizeURL = function(uri) { return this._load('sanitizeURL', uri); }; /** * Requests an image to include in the rendered scene. * This method proxies a call to ImageLoader.loadImage, but also tracks * image loading progress and invokes a re-render once complete. * @param {string} uri - The URI string of the image. * @return {Promise} - A Promise that resolves to the loaded Image. */ prototype$41.loadImage = function(uri) { return this._load('loadImage', uri); }; var point = function(event, el) { var rect = el.getBoundingClientRect(); return [ event.clientX - rect.left - (el.clientLeft || 0), event.clientY - rect.top - (el.clientTop || 0) ]; }; function CanvasHandler(loader) { Handler.call(this, loader); this._down = null; this._touch = null; this._first = true; } var prototype$42 = inherits(CanvasHandler, Handler); prototype$42.initialize = function(el, origin, obj) { // add event listeners var canvas = this._canvas = el && domFind(el, 'canvas'); if (canvas) { var that = this; this.events.forEach(function(type) { canvas.addEventListener(type, function(evt) { if (prototype$42[type]) { prototype$42[type].call(that, evt); } else { that.fire(type, evt); } }); }); } return Handler.prototype.initialize.call(this, el, origin, obj); }; prototype$42.canvas = function() { return this._canvas; }; // retrieve the current canvas context prototype$42.context = function() { return this._canvas.getContext('2d'); }; // supported events prototype$42.events = [ 'keydown', 'keypress', 'keyup', 'dragenter', 'dragleave', 'dragover', 'mousedown', 'mouseup', 'mousemove', 'mouseout', 'mouseover', 'click', 'dblclick', 'wheel', 'mousewheel', 'touchstart', 'touchmove', 'touchend' ]; // to keep old versions of firefox happy prototype$42.DOMMouseScroll = function(evt) { this.fire('mousewheel', evt); }; function move(moveEvent, overEvent, outEvent) { return function(evt) { var a = this._active, p = this.pickEvent(evt); if (p === a) { // active item and picked item are the same this.fire(moveEvent, evt); // fire move } else { // active item and picked item are different if (!a || !a.exit) { // fire out for prior active item // suppress if active item was removed from scene this.fire(outEvent, evt); } this._active = p; // set new active item this.fire(overEvent, evt); // fire over for new active item this.fire(moveEvent, evt); // fire move for new active item } }; } function inactive(type) { return function(evt) { this.fire(type, evt); this._active = null; }; } prototype$42.mousemove = move('mousemove', 'mouseover', 'mouseout'); prototype$42.dragover = move('dragover', 'dragenter', 'dragleave'); prototype$42.mouseout = inactive('mouseout'); prototype$42.dragleave = inactive('dragleave'); prototype$42.mousedown = function(evt) { this._down = this._active; this.fire('mousedown', evt); }; prototype$42.click = function(evt) { if (this._down === this._active) { this.fire('click', evt); this._down = null; } }; prototype$42.touchstart = function(evt) { this._touch = this.pickEvent(evt.changedTouches[0]); if (this._first) { this._active = this._touch; this._first = false; } this.fire('touchstart', evt, true); }; prototype$42.touchmove = function(evt) { this.fire('touchmove', evt, true); }; prototype$42.touchend = function(evt) { this.fire('touchend', evt, true); this._touch = null; }; // fire an event prototype$42.fire = function(type, evt, touch) { var a = touch ? this._touch : this._active, h = this._handlers[type], i, len; // if hyperlinked, handle link first if (type === 'click' && a && a.href) { this.handleHref(evt, a, a.href); } else if ((type === 'mouseover' || type === 'mouseout') && a && a.tooltip) { this.handleTooltip(evt, a, type === 'mouseover' ? a.tooltip : null); } // invoke all registered handlers if (h) { evt.vegaType = type; for (i=0, len=h.length; i<len; ++i) { h[i].handler.call(this._obj, evt, a); } } }; // add an event handler prototype$42.on = function(type, handler) { var name = this.eventName(type), h = this._handlers; (h[name] || (h[name] = [])).push({ type: type, handler: handler }); return this; }; // remove an event handler prototype$42.off = function(type, handler) { var name = this.eventName(type), h = this._handlers[name], i; if (!h) return; for (i=h.length; --i>=0;) { if (h[i].type !== type) continue; if (!handler || h[i].handler === handler) h.splice(i, 1); } return this; }; prototype$42.pickEvent = function(evt) { var p = point(evt, this._canvas), o = this._origin; return this.pick(this._scene, p[0], p[1], p[0] - o[0], p[1] - o[1]); }; // find the scenegraph item at the current mouse position // x, y -- the absolute x, y mouse coordinates on the canvas element // gx, gy -- the relative coordinates within the current group prototype$42.pick = function(scene, x, y, gx, gy) { var g = this.context(), mark = marks[scene.marktype]; return mark.pick.call(this, g, scene, x, y, gx, gy); }; var clip$1 = function(context, scene) { var group = scene.group; context.save(); context.beginPath(); context.rect(0, 0, group.width || 0, group.height || 0); context.clip(); }; var devicePixelRatio = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1; var resize = function(canvas, width, height, origin, scaleFactor) { var inDOM = typeof HTMLElement !== 'undefined' && canvas instanceof HTMLElement && canvas.parentNode != null; var context = canvas.getContext('2d'), ratio = inDOM ? devicePixelRatio : scaleFactor; canvas.width = width * ratio; canvas.height = height * ratio; if (inDOM && ratio !== 1) { canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; } context.pixelRatio = ratio; context.setTransform( ratio, 0, 0, ratio, ratio * origin[0], ratio * origin[1] ); return canvas; }; function CanvasRenderer(loader) { Renderer.call(this, loader); this._redraw = false; this._dirty = new Bounds(); } var prototype$43 = inherits(CanvasRenderer, Renderer); var base = Renderer.prototype; var tempBounds$1 = new Bounds(); prototype$43.initialize = function(el, width, height, origin, scaleFactor) { this._canvas = Canvas$1(1, 1); // instantiate a small canvas if (el) { domClear(el, 0).appendChild(this._canvas); this._canvas.setAttribute('class', 'marks'); } // this method will invoke resize to size the canvas appropriately return base.initialize.call(this, el, width, height, origin, scaleFactor); }; prototype$43.resize = function(width, height, origin, scaleFactor) { base.resize.call(this, width, height, origin, scaleFactor); resize(this._canvas, this._width, this._height, this._origin, this._scale); this._redraw = true; return this; }; prototype$43.canvas = function() { return this._canvas; }; prototype$43.context = function() { return this._canvas ? this._canvas.getContext('2d') : null; }; prototype$43.dirty = function(item) { var b = translate$1(item.bounds, item.mark.group); this._dirty.union(b); }; function clipToBounds(g, b, origin) { // expand bounds by 1 pixel, then round to pixel boundaries b.expand(1).round(); // to avoid artifacts translate if origin has fractional pixels b.translate(-(origin[0] % 1), -(origin[1] % 1)); // set clipping path g.beginPath(); g.rect(b.x1, b.y1, b.width(), b.height()); g.clip(); return b; } function translate$1(bounds, group) { if (group == null) return bounds; var b = tempBounds$1.clear().union(bounds); for (; group != null; group = group.mark.group) { b.translate(group.x || 0, group.y || 0); } return b; } prototype$43._render = function(scene) { var g = this.context(), o = this._origin, w = this._width, h = this._height, b = this._dirty; // setup g.save(); if (this._redraw || b.empty()) { this._redraw = false; b = null; } else { b = clipToBounds(g, b, o); } this.clear(-o[0], -o[1], w, h); // render this.draw(g, scene, b); // takedown g.restore(); this._dirty.clear(); return this; }; prototype$43.draw = function(ctx, scene, bounds) { var mark = marks[scene.marktype]; if (scene.clip) clip$1(ctx, scene); mark.draw.call(this, ctx, scene, bounds); if (scene.clip) ctx.restore(); }; prototype$43.clear = function(x, y, w, h) { var g = this.context(); g.clearRect(x, y, w, h); if (this._bgcolor != null) { g.fillStyle = this._bgcolor; g.fillRect(x, y, w, h); } }; function SVGHandler(loader) { Handler.call(this, loader); var h = this; h._hrefHandler = listener(h, function(evt, item) { if (item && item.href) h.handleHref(evt, item, item.href); }); h._tooltipHandler = listener(h, function(evt, item) { if (item && item.tooltip) { h.handleTooltip(evt, item, evt.type === 'mouseover' ? item.tooltip : null); } }); } var prototype$44 = inherits(SVGHandler, Handler); prototype$44.initialize = function(el, origin, obj) { var svg = this._svg; if (svg) { svg.removeEventListener('click', this._hrefHandler); svg.removeEventListener('mouseover', this._tooltipHandler); svg.removeEventListener('mouseout', this._tooltipHandler); } this._svg = svg = el && domFind(el, 'svg'); if (svg) { svg.addEventListener('click', this._hrefHandler); svg.addEventListener('mouseover', this._tooltipHandler); svg.addEventListener('mouseout', this._tooltipHandler); } return Handler.prototype.initialize.call(this, el, origin, obj); }; prototype$44.svg = function() { return this._svg; }; // wrap an event listener for the SVG DOM function listener(context, handler) { return function(evt) { var target = evt.target, item = target.__data__; evt.vegaType = evt.type; item = Array.isArray(item) ? item[0] : item; handler.call(context._obj, evt, item); }; } // add an event handler prototype$44.on = function(type, handler) { var name = this.eventName(type), h = this._handlers, x = { type: type, handler: handler, listener: listener(this, handler) }; (h[name] || (h[name] = [])).push(x); if (this._svg) { this._svg.addEventListener(name, x.listener); } return this; }; // remove an event handler prototype$44.off = function(type, handler) { var name = this.eventName(type), svg = this._svg, h = this._handlers[name], i; if (!h) return; for (i=h.length; --i>=0;) { if (h[i].type === type && !handler || h[i].handler === handler) { if (this._svg) { svg.removeEventListener(name, h[i].listener); } h.splice(i, 1); } } return this; }; // generate string for an opening xml tag // tag: the name of the xml tag // attr: hash of attribute name-value pairs to include // raw: additional raw string to include in tag markup function openTag(tag, attr, raw) { var s = '<' + tag, key, val; if (attr) { for (key in attr) { val = attr[key]; if (val != null) { s += ' ' + key + '="' + val + '"'; } } } if (raw) s += ' ' + raw; return s + '>'; } // generate string for closing xml tag // tag: the name of the xml tag function closeTag(tag) { return '</' + tag + '>'; } var metadata = { 'version': '1.1', 'xmlns': 'http://www.w3.org/2000/svg', 'xmlns:xlink': 'http://www.w3.org/1999/xlink' }; var styles = { 'fill': 'fill', 'fillOpacity': 'fill-opacity', 'stroke': 'stroke', 'strokeOpacity': 'stroke-opacity', 'strokeWidth': 'stroke-width', 'strokeCap': 'stroke-linecap', 'strokeJoin': 'stroke-linejoin', 'strokeDash': 'stroke-dasharray', 'strokeDashOffset': 'stroke-dashoffset', 'strokeMiterLimit': 'stroke-miterlimit', 'opacity': 'opacity' }; var styleProperties = Object.keys(styles); var ns = metadata.xmlns; function SVGRenderer(loader) { Renderer.call(this, loader); this._dirtyID = 1; this._dirty = []; this._svg = null; this._root = null; this._defs = null; } var prototype$45 = inherits(SVGRenderer, Renderer); var base$1 = Renderer.prototype; prototype$45.initialize = function(el, width, height, padding) { if (el) { this._svg = domChild(el, 0, 'svg', ns); this._svg.setAttribute('class', 'marks'); domClear(el, 1); // set the svg root group this._root = domChild(this._svg, 0, 'g', ns); domClear(this._svg, 1); } // create the svg definitions cache this._defs = { gradient: {}, clipping: {} }; // set background color if defined this.background(this._bgcolor); return base$1.initialize.call(this, el, width, height, padding); }; prototype$45.background = function(bgcolor) { if (arguments.length && this._svg) { this._svg.style.setProperty('background-color', bgcolor); } return base$1.background.apply(this, arguments); }; prototype$45.resize = function(width, height, origin, scaleFactor) { base$1.resize.call(this, width, height, origin, scaleFactor); if (this._svg) { this._svg.setAttribute('width', this._width * this._scale); this._svg.setAttribute('height', this._height * this._scale); this._svg.setAttribute('viewBox', '0 0 ' + this._width + ' ' + this._height); this._root.setAttribute('transform', 'translate(' + this._origin + ')'); } this._dirty = []; return this; }; prototype$45.svg = function() { if (!this._svg) return null; var attr = { class: 'marks', width: this._width * this._scale, height: this._height * this._scale, viewBox: '0 0 ' + this._width + ' ' + this._height }; for (var key$$1 in metadata) { attr[key$$1] = metadata[key$$1]; } var bg = !this._bgcolor ? '' : (openTag('rect', { width: this._width, height: this._height, style: 'fill: ' + this._bgcolor + ';' }) + closeTag('rect')); return openTag('svg', attr) + bg + this._svg.innerHTML + closeTag('svg'); }; // -- Render entry point -- prototype$45._render = function(scene) { // perform spot updates and re-render markup if (this._dirtyCheck()) { if (this._dirtyAll) this._resetDefs(); this.draw(this._root, scene); domClear(this._root, 1); } this.updateDefs(); this._dirty = []; ++this._dirtyID; return this; }; // -- Manage SVG definitions ('defs') block -- prototype$45.updateDefs = function() { var svg = this._svg, defs = this._defs, el = defs.el, index = 0, id$$1; for (id$$1 in defs.gradient) { if (!el) defs.el = (el = domChild(svg, 0, 'defs', ns)); updateGradient(el, defs.gradient[id$$1], index++); } for (id$$1 in defs.clipping) { if (!el) defs.el = (el = domChild(svg, 0, 'defs', ns)); updateClipping(el, defs.clipping[id$$1], index++); } // clean-up if (el) { if (index === 0) { svg.removeChild(el); defs.el = null; } else { domClear(el, index); } } }; function updateGradient(el, grad, index) { var i, n, stop; el = domChild(el, index, 'linearGradient', ns); el.setAttribute('id', grad.id); el.setAttribute('x1', grad.x1); el.setAttribute('x2', grad.x2); el.setAttribute('y1', grad.y1); el.setAttribute('y2', grad.y2); for (i=0, n=grad.stops.length; i<n; ++i) { stop = domChild(el, i, 'stop', ns); stop.setAttribute('offset', grad.stops[i].offset); stop.setAttribute('stop-color', grad.stops[i].color); } domClear(el, i); } function updateClipping(el, clip$$1, index) { var rect; el = domChild(el, index, 'clipPath', ns); el.setAttribute('id', clip$$1.id); rect = domChild(el, 0, 'rect', ns); rect.setAttribute('x', 0); rect.setAttribute('y', 0); rect.setAttribute('width', clip$$1.width); rect.setAttribute('height', clip$$1.height); } prototype$45._resetDefs = function() { var def = this._defs; def.gradient = {}; def.clipping = {}; }; // -- Manage rendering of items marked as dirty -- prototype$45.dirty = function(item) { if (item.dirty !== this._dirtyID) { item.dirty = this._dirtyID; this._dirty.push(item); } }; prototype$45.isDirty = function(item) { return this._dirtyAll || !item._svg || item.dirty === this._dirtyID; }; prototype$45._dirtyCheck = function() { this._dirtyAll = true; var items = this._dirty; if (!items.length) return true; var id$$1 = ++this._dirtyID, item, mark, type, mdef, i, n, o; for (i=0, n=items.length; i<n; ++i) { item = items[i]; mark = item.mark; if (mark.marktype !== type) { // memoize mark instance lookup type = mark.marktype; mdef = marks[type]; } if (mark.zdirty && mark.dirty !== id$$1) { this._dirtyAll = false; mark.dirty = id$$1; dirtyParents(mark.group, id$$1); } if (item.exit) { // EXIT if (mdef.nested && mark.items.length) { // if nested mark with remaining points, update instead o = mark.items[0]; if (o._svg) this._update(mdef, o._svg, o); } else if (item._svg) { // otherwise remove from DOM o = item._svg.parentNode; if (o) o.removeChild(item._svg); } item._svg = null; continue; } item = (mdef.nested ? mark.items[0] : item); if (item._update === id$$1) continue; // already visited if (!item._svg || !item._svg.ownerSVGElement) { // ENTER this._dirtyAll = false; dirtyParents(item, id$$1); } else { // IN-PLACE UPDATE this._update(mdef, item._svg, item); } item._update = id$$1; } return !this._dirtyAll; }; function dirtyParents(item, id$$1) { for (; item && item.dirty !== id$$1; item=item.mark.group) { item.dirty = id$$1; if (item.mark && item.mark.dirty !== id$$1) { item.mark.dirty = id$$1; } else return; } } // -- Construct & maintain scenegraph to SVG mapping --- // Draw a mark container. prototype$45.draw = function(el, scene, prev) { if (!this.isDirty(scene)) return scene._svg; var renderer = this, mdef = marks[scene.marktype], events = scene.interactive === false ? 'none' : null, isGroup = mdef.tag === 'g', sibling = null, i = 0, parent; parent = bind(scene, el, prev, 'g'); parent.setAttribute('class', cssClass(scene)); if (!isGroup && events) { parent.style.setProperty('pointer-events', events); } if (scene.clip) { parent.setAttribute('clip-path', clip(renderer, scene, scene.group)); } function process(item) { var dirty = renderer.isDirty(item), node = bind(item, parent, sibling, mdef.tag); if (dirty) { renderer._update(mdef, node, item); if (isGroup) recurse(renderer, node, item); } sibling = node; ++i; } if (mdef.nested) { if (scene.items.length) process(scene.items[0]); } else { visit(scene, process); } domClear(parent, i); return parent; }; // Recursively process group contents. function recurse(renderer, el, group) { el = el.lastChild; var prev, idx = 0; visit(group, function(item) { prev = renderer.draw(el, item, prev); ++idx; }); // remove any extraneous DOM elements domClear(el, 1 + idx); } // Bind a scenegraph item to an SVG DOM element. // Create new SVG elements as needed. function bind(item, el, sibling, tag) { var node = item._svg, doc; // create a new dom node if needed if (!node) { doc = el.ownerDocument; node = domCreate(doc, tag, ns); item._svg = node; if (item.mark) { node.__data__ = item; node.__values__ = {fill: 'default'}; // if group, create background and foreground elements if (tag === 'g') { var bg = domCreate(doc, 'path', ns); bg.setAttribute('class', 'background'); node.appendChild(bg); bg.__data__ = item; var fg = domCreate(doc, 'g', ns); node.appendChild(fg); fg.__data__ = item; } } } if (doc || node.previousSibling !== sibling || !sibling) { el.insertBefore(node, sibling ? sibling.nextSibling : el.firstChild); } return node; } // -- Set attributes & styles on SVG elements --- var element = null; var values = null; // temp var for current values hash // Extra configuration for certain mark types var mark_extras = { group: function(mdef, el, item) { values = el.__values__; // use parent's values hash element = el.childNodes[1]; mdef.foreground(emit, item, this); element = el.childNodes[0]; mdef.background(emit, item, this); var value = item.mark.interactive === false ? 'none' : null; if (value !== values.events) { element.style.setProperty('pointer-events', value); values.events = value; } }, text: function(mdef, el, item) { var str = textValue(item); if (str !== values.text) { el.textContent = str; values.text = str; } str = font(item); if (str !== values.font) { el.style.setProperty('font', str); values.font = str; } } }; prototype$45._update = function(mdef, el, item) { // set dom element and values cache // provides access to emit method element = el; values = el.__values__; // apply svg attributes mdef.attr(emit, item, this); // some marks need special treatment var extra = mark_extras[mdef.type]; if (extra) extra.call(this, mdef, el, item); // apply svg css styles // note: element may be modified by 'extra' method this.style(element, item); }; function emit(name, value, ns) { // early exit if value is unchanged if (value === values[name]) return; if (value != null) { // if value is provided, update DOM attribute if (ns) { element.setAttributeNS(ns, name, value); } else { element.setAttribute(name, value); } } else { // else remove DOM attribute if (ns) { element.removeAttributeNS(ns, name); } else { element.removeAttribute(name); } } // note current value for future comparison values[name] = value; } prototype$45.style = function(el, o) { if (o == null) return; var i, n, prop, name, value; for (i=0, n=styleProperties.length; i<n; ++i) { prop = styleProperties[i]; value = o[prop]; if (value === values[prop]) continue; name = styles[prop]; if (value == null) { if (name === 'fill') { el.style.setProperty(name, 'none'); } else { el.style.removeProperty(name); } } else { if (value.id) { // ensure definition is included this._defs.gradient[value.id] = value; value = 'url(' + href() + '#' + value.id + ')'; } el.style.setProperty(name, value+''); } values[prop] = value; } }; function href() { var loc; return typeof window === 'undefined' ? '' : (loc = window.location).hash ? loc.href.slice(0, -loc.hash.length) : loc.href; } function SVGStringRenderer(loader) { Renderer.call(this, loader); this._text = { head: '', bg: '', root: '', foot: '', defs: '', body: '' }; this._defs = { gradient: {}, clipping: {} }; } var prototype$46 = inherits(SVGStringRenderer, Renderer); var base$2 = Renderer.prototype; prototype$46.resize = function(width, height, origin, scaleFactor) { base$2.resize.call(this, width, height, origin, scaleFactor); var o = this._origin, t = this._text; var attr = { class: 'marks', width: this._width * this._scale, height: this._height * this._scale, viewBox: '0 0 ' + this._width + ' ' + this._height }; for (var key$$1 in metadata) { attr[key$$1] = metadata[key$$1]; } t.head = openTag('svg', attr); var bg = this._bgcolor; if (bg === 'transparent' || bg === 'none') bg = null; if (bg) { t.bg = openTag('rect', { width: this._width, height: this._height, style: 'fill: ' + bg + ';' }) + closeTag('rect'); } else { t.bg = ''; } t.root = openTag('g', { transform: 'translate(' + o + ')' }); t.foot = closeTag('g') + closeTag('svg'); return this; }; prototype$46.background = function() { var rv = base$2.background.apply(this, arguments); if (arguments.length && this._text.head) { this.resize(this._width, this._height, this._origin, this._scale); } return rv; }; prototype$46.svg = function() { var t = this._text; return t.head + t.bg + t.defs + t.root + t.body + t.foot; }; prototype$46._render = function(scene) { this._text.body = this.mark(scene); this._text.defs = this.buildDefs(); return this; }; prototype$46.buildDefs = function() { var all = this._defs, defs = '', i, id$$1, def, stops; for (id$$1 in all.gradient) { def = all.gradient[id$$1]; stops = def.stops; defs += openTag('linearGradient', { id: id$$1, x1: def.x1, x2: def.x2, y1: def.y1, y2: def.y2 }); for (i=0; i<stops.length; ++i) { defs += openTag('stop', { offset: stops[i].offset, 'stop-color': stops[i].color }) + closeTag('stop'); } defs += closeTag('linearGradient'); } for (id$$1 in all.clipping) { def = all.clipping[id$$1]; defs += openTag('clipPath', {id: id$$1}); defs += openTag('rect', { x: 0, y: 0, width: def.width, height: def.height }) + closeTag('rect'); defs += closeTag('clipPath'); } return (defs.length > 0) ? openTag('defs') + defs + closeTag('defs') : ''; }; var object$1; function emit$1(name, value, ns, prefixed) { object$1[prefixed || name] = value; } prototype$46.attributes = function(attr, item) { object$1 = {}; attr(emit$1, item, this); return object$1; }; prototype$46.href = function(item) { var that = this, href = item.href, attr; if (href) { if (attr = that._hrefs && that._hrefs[href]) { return attr; } else { that.sanitizeURL(href).then(function(attr) { // rewrite to use xlink namespace // note that this will be deprecated in SVG 2.0 attr['xlink:href'] = attr.href; attr.href = null; (that._hrefs || (that._hrefs = {}))[href] = attr; }); } } return null; }; prototype$46.mark = function(scene) { var renderer = this, mdef = marks[scene.marktype], tag = mdef.tag, defs = this._defs, str = '', style; if (tag !== 'g' && scene.interactive === false) { style = 'style="pointer-events: none;"'; } // render opening group tag str += openTag('g', { 'class': cssClass(scene), 'clip-path': scene.clip ? clip(renderer, scene, scene.group) : null }, style); // render contained elements function process(item) { var href = renderer.href(item); if (href) str += openTag('a', href); style = (tag !== 'g') ? applyStyles(item, scene, tag, defs) : null; str += openTag(tag, renderer.attributes(mdef.attr, item), style); if (tag === 'text') { str += escape_text(textValue(item)); } else if (tag === 'g') { str += openTag('path', renderer.attributes(mdef.background, item), applyStyles(item, scene, 'bgrect', defs)) + closeTag('path'); str += openTag('g', renderer.attributes(mdef.foreground, item)) + renderer.markGroup(item) + closeTag('g'); } str += closeTag(tag); if (href) str += closeTag('a'); } if (mdef.nested) { if (scene.items && scene.items.length) process(scene.items[0]); } else { visit(scene, process); } // render closing group tag return str + closeTag('g'); }; prototype$46.markGroup = function(scene) { var renderer = this, str = ''; visit(scene, function(item) { str += renderer.mark(item); }); return str; }; function applyStyles(o, mark, tag, defs) { if (o == null) return ''; var i, n, prop, name, value, s = ''; if (tag === 'bgrect' && mark.interactive === false) { s += 'pointer-events: none; '; } if (tag === 'text') { s += 'font: ' + font(o) + '; '; } for (i=0, n=styleProperties.length; i<n; ++i) { prop = styleProperties[i]; name = styles[prop]; value = o[prop]; if (value == null) { if (name === 'fill') { s += 'fill: none; '; } } else if (value === 'transparent' && (name === 'fill' || name === 'stroke')) { // transparent is not a legal SVG value, so map to none instead s += name + ': none; '; } else { if (value.id) { // ensure definition is included defs.gradient[value.id] = value; value = 'url(#' + value.id + ')'; } s += name + ': ' + value + '; '; } } return s ? 'style="' + s.trim() + '"' : null; } function escape_text(s) { return s.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } var Canvas$2 = 'canvas'; var PNG = 'png'; var SVG = 'svg'; var None$1 = 'none'; var RenderType = { Canvas: Canvas$2, PNG: PNG, SVG: SVG, None: None$1 }; var modules = {}; modules[Canvas$2] = modules[PNG] = { renderer: CanvasRenderer, headless: CanvasRenderer, handler: CanvasHandler }; modules[SVG] = { renderer: SVGRenderer, headless: SVGStringRenderer, handler: SVGHandler }; modules[None$1] = {}; function renderModule(name, _$$1) { name = String(name || '').toLowerCase(); if (arguments.length > 1) { modules[name] = _$$1; return this; } else { return modules[name]; } } var TOLERANCE = 1e-9; function sceneEqual(a, b, key$$1) { return (a === b) ? true : (key$$1 === 'path') ? pathEqual(a, b) : (a instanceof Date && b instanceof Date) ? +a === +b : (isNumber(a) && isNumber(b)) ? Math.abs(a - b) <= TOLERANCE : (!a || !b || !isObject(a) && !isObject(b)) ? a == b : (a == null || b == null) ? false : objectEqual(a, b); } function pathEqual(a, b) { return sceneEqual(pathParse(a), pathParse(b)); } function objectEqual(a, b) { var ka = Object.keys(a), kb = Object.keys(b), key$$1, i; if (ka.length !== kb.length) return false; ka.sort(); kb.sort(); for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } for (i = ka.length - 1; i >= 0; i--) { key$$1 = ka[i]; if (!sceneEqual(a[key$$1], b[key$$1], key$$1)) return false; } return typeof a === typeof b; } /** * Calculate bounding boxes for scenegraph items. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.mark - The scenegraph mark instance to bound. */ function Bound(params) { Transform.call(this, null, params); } var prototype$36 = inherits(Bound, Transform); var temp = new Bounds(); prototype$36.transform = function(_$$1, pulse) { var view = pulse.dataflow, mark = _$$1.mark, type = mark.marktype, entry = marks[type], bound = entry.bound, clip = mark.clip, markBounds = mark.bounds, rebound; if (entry.nested) { // multi-item marks have a single bounds instance if (mark.items.length) view.dirty(mark.items[0]); markBounds = boundItem(mark, bound); mark.items.forEach(function(item) { item.bounds.clear().union(markBounds); }); } else if (type === 'group' || _$$1.modified()) { // operator parameters modified -> re-bound all items // updates group bounds in response to modified group content pulse.visit(pulse.MOD, function(item) { view.dirty(item); }); markBounds.clear(); mark.items.forEach(function(item) { markBounds.union(boundItem(item, bound)); }); } else { // incrementally update bounds, re-bound mark as needed rebound = pulse.changed(pulse.REM); pulse.visit(pulse.ADD, function(item) { markBounds.union(boundItem(item, bound)); }); pulse.visit(pulse.MOD, function(item) { rebound = rebound || markBounds.alignsWith(item.bounds); view.dirty(item); markBounds.union(boundItem(item, bound)); }); if (rebound && !clip) { markBounds.clear(); mark.items.forEach(function(item) { markBounds.union(item.bounds); }); } } if (clip) { markBounds.intersect(temp.set(0, 0, mark.group.width, mark.group.height)); } return pulse.modifies('bounds'); }; function boundItem(item, bound, opt) { return bound(item.bounds.clear(), item, opt); } var COUNTER_NAME = ':vega_identifier:'; /** * Adds a unique identifier to all added tuples. * This transform creates a new signal that serves as an id counter. * As a result, the id counter is shared across all instances of this * transform, generating unique ids across multiple data streams. In * addition, this signal value can be included in a snapshot of the * dataflow state, enabling correct resumption of id allocation. * @constructor * @param {object} params - The parameters for this operator. * @param {string} params.as - The field name for the generated identifier. */ function Identifier(params) { Transform.call(this, 0, params); } Identifier.Definition = { "type": "Identifier", "metadata": {"modifies": true}, "params": [ { "name": "as", "type": "string", "required": true } ] }; var prototype$47 = inherits(Identifier, Transform); prototype$47.transform = function(_$$1, pulse) { var counter = getCounter(pulse.dataflow), id$$1 = counter.value, as = _$$1.as; pulse.visit(pulse.ADD, function(t) { if (!t[as]) t[as] = ++id$$1; }); counter.set(this.value = id$$1); return pulse; }; function getCounter(view) { var counter = view._signals[COUNTER_NAME]; if (!counter) { view._signals[COUNTER_NAME] = (counter = view.add(0)); } return counter; } /** * Bind scenegraph items to a scenegraph mark instance. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.markdef - The mark definition for creating the mark. * This is an object of legal scenegraph mark properties which *must* include * the 'marktype' property. * @param {Array<number>} params.scenepath - Scenegraph tree coordinates for the mark. * The path is an array of integers, each indicating the index into * a successive chain of items arrays. */ function Mark(params) { Transform.call(this, null, params); } var prototype$48 = inherits(Mark, Transform); prototype$48.transform = function(_$$1, pulse) { var mark = this.value; // acquire mark on first invocation, bind context and group if (!mark) { mark = pulse.dataflow.scenegraph().mark(_$$1.markdef, lookup$1(_$$1), _$$1.index); mark.group.context = _$$1.context; if (!_$$1.context.group) _$$1.context.group = mark.group; mark.source = this; this.value = mark; } // initialize entering items var Init = mark.marktype === 'group' ? GroupItem : Item; pulse.visit(pulse.ADD, function(item) { Init.call(item, mark); }); // bind items array to scenegraph mark mark.items = pulse.source; return pulse; }; function lookup$1(_$$1) { var g = _$$1.groups, p = _$$1.parent; return g && g.size === 1 ? g.get(Object.keys(g.object)[0]) : g && p ? g.lookup(p) : null; } var Top = 'top'; var Left = 'left'; var Right = 'right'; var Bottom = 'bottom'; /** * Analyze items for overlap, changing opacity to hide items with * overlapping bounding boxes. This transform will preserve at least * two items (e.g., first and last) even if overlap persists. * @param {object} params - The parameters for this operator. * @param {function(*,*): number} [params.sort] - A comparator * function for sorting items. * @param {object} [params.method] - The overlap removal method to apply. * One of 'parity' (default, hide every other item until there is no * more overlap) or 'greedy' (sequentially scan and hide and items that * overlap with the last visible item). * @param {object} [params.boundScale] - A scale whose range should be used * to bound the items. Items exceeding the bounds of the scale range * will be treated as overlapping. If null or undefined, no bounds check * will be applied. * @param {object} [params.boundOrient] - The orientation of the scale * (top, bottom, left, or right) used to bound items. This parameter is * ignored if boundScale is null or undefined. * @param {object} [params.boundTolerance] - The tolerance in pixels for * bound inclusion testing (default 1). This specifies by how many pixels * an item's bounds may exceed the scale range bounds and not be culled. * @constructor */ function Overlap(params) { Transform.call(this, null, params); } var prototype$49 = inherits(Overlap, Transform); var methods = { parity: function(items) { return items.filter(function(item, i) { return i % 2 ? (item.opacity = 0) : 1; }); }, greedy: function(items) { var a; return items.filter(function(b, i) { if (!i || !intersect(a.bounds, b.bounds)) { a = b; return 1; } else { return b.opacity = 0; } }); } }; // compute bounding box intersection // allow 1 pixel of overlap tolerance function intersect(a, b) { return !( a.x2 - 1 < b.x1 || a.x1 + 1 > b.x2 || a.y2 - 1 < b.y1 || a.y1 + 1 > b.y2 ); } function hasOverlap(items) { for (var i=1, n=items.length, a=items[0].bounds, b; i<n; a=b, ++i) { if (intersect(a, b = items[i].bounds)) return true; } } function hasBounds(item) { var b = item.bounds; return b.width() > 1 && b.height() > 1; } function boundTest(scale, orient, tolerance) { var range$$1 = scale.range(), b = new Bounds(); if (orient === Top || orient === Bottom) { b.set(range$$1[0], -Infinity, range$$1[1], +Infinity); } else { b.set(-Infinity, range$$1[0], +Infinity, range$$1[1]); } b.expand(tolerance || 1); return function(item) { return b.encloses(item.bounds); }; } prototype$49.transform = function(_$$1, pulse) { var reduce = methods[_$$1.method] || methods.parity, source = pulse.materialize(pulse.SOURCE).source; if (!source) return; if (_$$1.sort) { source = source.slice().sort(_$$1.sort); } if (_$$1.method === 'greedy') { source = source.filter(hasBounds); } // reset all items to be fully opaque source.forEach(function(item) { item.opacity = 1; }); var items = source; if (items.length >= 3 && hasOverlap(items)) { pulse = pulse.reflow(_$$1.modified()).modifies('opacity'); do { items = reduce(items); } while (items.length >= 3 && hasOverlap(items)); if (items.length < 3 && !peek(source).opacity) { if (items.length > 1) peek(items).opacity = 0; peek(source).opacity = 1; } } if (_$$1.boundScale) { var test = boundTest(_$$1.boundScale, _$$1.boundOrient, _$$1.boundTolerance); source.forEach(function(item) { if (!test(item)) item.opacity = 0; }); } return pulse; }; /** * Queue modified scenegraph items for rendering. * @constructor */ function Render(params) { Transform.call(this, null, params); } var prototype$50 = inherits(Render, Transform); prototype$50.transform = function(_$$1, pulse) { var view = pulse.dataflow; pulse.visit(pulse.ALL, function(item) { view.dirty(item); }); // set z-index dirty flag as needed if (pulse.fields && pulse.fields['zindex']) { var item = pulse.source && pulse.source[0]; if (item) item.mark.zdirty = true; } }; var AxisRole$1 = 'axis'; var LegendRole$1 = 'legend'; var RowHeader$1 = 'row-header'; var RowFooter$1 = 'row-footer'; var RowTitle = 'row-title'; var ColHeader$1 = 'column-header'; var ColFooter$1 = 'column-footer'; var ColTitle = 'column-title'; function extractGroups(group) { var groups = group.items, n = groups.length, i = 0, mark, items; var views = { marks: [], rowheaders: [], rowfooters: [], colheaders: [], colfooters: [], rowtitle: null, coltitle: null }; // layout axes, gather legends, collect bounds for (; i<n; ++i) { mark = groups[i]; items = mark.items; if (mark.marktype === 'group') { switch (mark.role) { case AxisRole$1: case LegendRole$1: break; case RowHeader$1: addAll(items, views.rowheaders); break; case RowFooter$1: addAll(items, views.rowfooters); break; case ColHeader$1: addAll(items, views.colheaders); break; case ColFooter$1: addAll(items, views.colfooters); break; case RowTitle: views.rowtitle = items[0]; break; case ColTitle: views.coltitle = items[0]; break; default: addAll(items, views.marks); } } } return views; } function addAll(items, array$$1) { for (var i=0, n=items.length; i<n; ++i) { array$$1.push(items[i]); } } function bboxFlush(item) { return {x1: 0, y1: 0, x2: item.width || 0, y2: item.height || 0}; } function bboxFull(item) { var b = item.bounds.clone(); return b.empty() ? b.set(0, 0, 0, 0) : b.translate(-(item.x||0), -(item.y||0)); } function boundFlush(item, field$$1) { return field$$1 === 'x1' ? (item.x || 0) : field$$1 === 'y1' ? (item.y || 0) : field$$1 === 'x2' ? (item.x || 0) + (item.width || 0) : field$$1 === 'y2' ? (item.y || 0) + (item.height || 0) : undefined; } function boundFull(item, field$$1) { return item.bounds[field$$1]; } function get(opt, key$$1, d) { var v = isObject(opt) ? opt[key$$1] : opt; return v != null ? v : (d !== undefined ? d : 0); } function offsetValue(v) { return v < 0 ? Math.ceil(-v) : 0; } function gridLayout(view, group, opt) { var views = extractGroups(group, opt), groups = views.marks, flush = opt.bounds === 'flush', bbox = flush ? bboxFlush : bboxFull, bounds = new Bounds(0, 0, 0, 0), alignCol = get(opt.align, 'column'), alignRow = get(opt.align, 'row'), padCol = get(opt.padding, 'column'), padRow = get(opt.padding, 'row'), off = opt.offset, ncols = group.columns || opt.columns || groups.length, nrows = ncols < 0 ? 1 : Math.ceil(groups.length / ncols), cells = nrows * ncols, xOffset = [], xExtent = [], xInit = 0, yOffset = [], yExtent = [], yInit = 0, n = groups.length, m, i, c, r, b, g, px, py, x, y, band, extent$$1, offset; for (i=0; i<ncols; ++i) { xExtent[i] = 0; } for (i=0; i<nrows; ++i) { yExtent[i] = 0; } // determine offsets for each group for (i=0; i<n; ++i) { b = bbox(groups[i]); c = i % ncols; r = ~~(i / ncols); px = c ? Math.ceil(bbox(groups[i-1]).x2): 0; py = r ? Math.ceil(bbox(groups[i-ncols]).y2): 0; xExtent[c] = Math.max(xExtent[c], px); yExtent[r] = Math.max(yExtent[r], py); xOffset.push(padCol + offsetValue(b.x1)); yOffset.push(padRow + offsetValue(b.y1)); view.dirty(groups[i]); } // set initial alignment offsets for (i=0; i<n; ++i) { if (i % ncols === 0) xOffset[i] = xInit; if (i < ncols) yOffset[i] = yInit; } // enforce column alignment constraints if (alignCol === 'each') { for (c=1; c<ncols; ++c) { for (offset=0, i=c; i<n; i += ncols) { if (offset < xOffset[i]) offset = xOffset[i]; } for (i=c; i<n; i += ncols) { xOffset[i] = offset + xExtent[c]; } } } else if (alignCol === 'all') { for (extent$$1=0, c=1; c<ncols; ++c) { if (extent$$1 < xExtent[c]) extent$$1 = xExtent[c]; } for (offset=0, i=0; i<n; ++i) { if (i % ncols && offset < xOffset[i]) offset = xOffset[i]; } for (i=0; i<n; ++i) { if (i % ncols) xOffset[i] = offset + extent$$1; } } else { for (c=1; c<ncols; ++c) { for (i=c; i<n; i += ncols) { xOffset[i] += xExtent[c]; } } } // enforce row alignment constraints if (alignRow === 'each') { for (r=1; r<nrows; ++r) { for (offset=0, i=r*ncols, m=i+ncols; i<m; ++i) { if (offset < yOffset[i]) offset = yOffset[i]; } for (i=r*ncols; i<m; ++i) { yOffset[i] = offset + yExtent[r]; } } } else if (alignRow === 'all') { for (extent$$1=0, r=1; r<nrows; ++r) { if (extent$$1 < yExtent[r]) extent$$1 = yExtent[r]; } for (offset=0, i=ncols; i<n; ++i) { if (offset < yOffset[i]) offset = yOffset[i]; } for (i=ncols; i<n; ++i) { yOffset[i] = offset + extent$$1; } } else { for (r=1; r<nrows; ++r) { for (i=r*ncols, m=i+ncols; i<m; ++i) { yOffset[i] += yExtent[r]; } } } // perform horizontal grid layout for (x=0, i=0; i<n; ++i) { g = groups[i]; px = g.x || 0; g.x = (x = xOffset[i] + (i % ncols ? x : 0)); g.bounds.translate(x - px, 0); } // perform vertical grid layout for (c=0; c<ncols; ++c) { for (y=0, i=c; i<n; i += ncols) { g = groups[i]; py = g.y || 0; g.y = (y += yOffset[i]); g.bounds.translate(0, y - py); } } // update mark bounds, mark dirty for (i=0; i<n; ++i) groups[i].mark.bounds.clear(); for (i=0; i<n; ++i) { g = groups[i]; view.dirty(g); bounds.union(g.mark.bounds.union(g.bounds)); } // -- layout grid headers and footers -- // aggregation functions for grid margin determination function min$$1(a, b) { return Math.floor(Math.min(a, b)); } function max$$1(a, b) { return Math.ceil(Math.max(a, b)); } // bounding box calculation methods bbox = flush ? boundFlush : boundFull; // perform row header layout band = get(opt.headerBand, 'row', null); x = layoutHeaders(view, views.rowheaders, groups, ncols, nrows, -get(off, 'rowHeader'), min$$1, 0, bbox, 'x1', 0, ncols, 1, band); // perform column header layout band = get(opt.headerBand, 'column', null); y = layoutHeaders(view, views.colheaders, groups, ncols, ncols, -get(off, 'columnHeader'), min$$1, 1, bbox, 'y1', 0, 1, ncols, band); // perform row footer layout band = get(opt.footerBand, 'row', null); layoutHeaders( view, views.rowfooters, groups, ncols, nrows, get(off, 'rowFooter'), max$$1, 0, bbox, 'x2', ncols-1, ncols, 1, band); // perform column footer layout band = get(opt.footerBand, 'column', null); layoutHeaders( view, views.colfooters, groups, ncols, ncols, get(off, 'columnFooter'), max$$1, 1, bbox, 'y2', cells-ncols, 1, ncols, band); // perform row title layout if (views.rowtitle) { offset = x - get(off, 'rowTitle'); band = get(opt.titleBand, 'row', 0.5); layoutTitle$1(view, views.rowtitle, offset, 0, bounds, band); } // perform column title layout if (views.coltitle) { offset = y - get(off, 'columnTitle'); band = get(opt.titleBand, 'column', 0.5); layoutTitle$1(view, views.coltitle, offset, 1, bounds, band); } } function layoutHeaders(view, headers, groups, ncols, limit, offset, agg, isX, bound, bf, start, stride, back, band) { var n = groups.length, init = 0, edge = 0, i, j, k, m, b, h, g, x, y; // if no groups, early exit and return 0 if (!n) return init; // compute margin for (i=start; i<n; i+=stride) { if (groups[i]) init = agg(init, bound(groups[i], bf)); } // if no headers, return margin calculation if (!headers.length) return init; // check if number of headers exceeds number of rows or columns if (headers.length > limit) { view.warn('Grid headers exceed limit: ' + limit); headers = headers.slice(0, limit); } // apply offset init += offset; // clear mark bounds for all headers for (j=0, m=headers.length; j<m; ++j) { view.dirty(headers[j]); headers[j].mark.bounds.clear(); } // layout each header for (i=start, j=0, m=headers.length; j<m; ++j, i+=stride) { h = headers[j]; b = h.mark.bounds; // search for nearest group to align to // necessary if table has empty cells for (k=i; k >= 0 && (g = groups[k]) == null; k-=back); // assign coordinates and update bounds if (isX) { x = band == null ? g.x : Math.round(g.bounds.x1 + band * g.bounds.width()); y = init; } else { x = init; y = band == null ? g.y : Math.round(g.bounds.y1 + band * g.bounds.height()); } b.union(h.bounds.translate(x - (h.x || 0), y - (h.y || 0))); h.x = x; h.y = y; view.dirty(h); // update current edge of layout bounds edge = agg(edge, b[bf]); } return edge; } function layoutTitle$1(view, g, offset, isX, bounds, band) { if (!g) return; view.dirty(g); // compute title coordinates var x = offset, y = offset; isX ? (x = Math.round(bounds.x1 + band * bounds.width())) : (y = Math.round(bounds.y1 + band * bounds.height())); // assign coordinates and update bounds g.bounds.translate(x - (g.x || 0), y - (g.y || 0)); g.mark.bounds.clear().union(g.bounds); g.x = x; g.y = y; // queue title for redraw view.dirty(g); } var Fit = 'fit'; var Pad = 'pad'; var None$2 = 'none'; var Padding = 'padding'; var AxisRole = 'axis'; var TitleRole = 'title'; var FrameRole = 'frame'; var LegendRole = 'legend'; var ScopeRole = 'scope'; var RowHeader = 'row-header'; var RowFooter = 'row-footer'; var ColHeader = 'column-header'; var ColFooter = 'column-footer'; var AxisOffset = 0.5; var tempBounds$2 = new Bounds(); /** * Layout view elements such as axes and legends. * Also performs size adjustments. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.mark - Scenegraph mark of groups to layout. */ function ViewLayout(params) { Transform.call(this, null, params); } var prototype$51 = inherits(ViewLayout, Transform); prototype$51.transform = function(_$$1, pulse) { // TODO incremental update, output? var view = pulse.dataflow; _$$1.mark.items.forEach(function(group) { if (_$$1.layout) gridLayout(view, group, _$$1.layout); layoutGroup(view, group, _$$1); }); return pulse; }; function layoutGroup(view, group, _$$1) { var items = group.items, width = Math.max(0, group.width || 0), height = Math.max(0, group.height || 0), viewBounds = new Bounds().set(0, 0, width, height), axisBounds = viewBounds.clone(), xBounds = viewBounds.clone(), yBounds = viewBounds.clone(), legends = [], title, mark, flow, b, i, n; // layout axes, gather legends, collect bounds for (i=0, n=items.length; i<n; ++i) { mark = items[i]; switch (mark.role) { case AxisRole: axisBounds.union(b = layoutAxis(view, mark, width, height)); (isYAxis(mark) ? xBounds : yBounds).union(b); break; case TitleRole: title = mark; break; case LegendRole: legends.push(mark); break; case FrameRole: case ScopeRole: case RowHeader: case RowFooter: case ColHeader: case ColFooter: xBounds.union(mark.bounds); yBounds.union(mark.bounds); break; default: viewBounds.union(mark.bounds); } } // layout title, adjust bounds if (title) { axisBounds.union(b = layoutTitle(view, title, axisBounds)); (isYAxis(title) ? xBounds : yBounds).union(b); } // layout legends, adjust viewBounds if (legends.length) { flow = {left: 0, right: 0, top: 0, bottom: 0, margin: _$$1.legendMargin || 8}; for (i=0, n=legends.length; i<n; ++i) { b = layoutLegend(view, legends[i], flow, xBounds, yBounds, width, height); if (_$$1.autosize && _$$1.autosize.type === Fit) { // for autosize fit, incorporate the orthogonal dimension only // legends that overrun the chart area will then be clipped // otherwise the chart area gets reduced to nothing! var orient = legends[i].items[0].datum.orient; if (orient === Left || orient === Right) { viewBounds.add(b.x1, 0).add(b.x2, 0); } else if (orient === Top || orient === Bottom) { viewBounds.add(0, b.y1).add(0, b.y2); } } else { viewBounds.union(b); } } } // perform size adjustment viewBounds.union(xBounds).union(yBounds).union(axisBounds); layoutSize(view, group, viewBounds, _$$1); } function set(item, property, value) { if (item[property] === value) { return 0; } else { item[property] = value; return 1; } } function isYAxis(mark) { var orient = mark.items[0].datum.orient; return orient === Left || orient === Right; } function axisIndices(datum) { var index = +datum.grid; return [ datum.ticks ? index++ : -1, // ticks index datum.labels ? index++ : -1, // labels index index + (+datum.domain) // title index ]; } function layoutAxis(view, axis, width, height) { var item = axis.items[0], datum = item.datum, orient = datum.orient, indices = axisIndices(datum), range$$1 = item.range, offset = item.offset, position = item.position, minExtent = item.minExtent, maxExtent = item.maxExtent, title = datum.title && item.items[indices[2]].items[0], titlePadding = item.titlePadding, bounds = item.bounds, x = 0, y = 0, i, s; tempBounds$2.clear().union(bounds); bounds.clear(); if ((i=indices[0]) > -1) bounds.union(item.items[i].bounds); if ((i=indices[1]) > -1) bounds.union(item.items[i].bounds); // position axis group and title switch (orient) { case Top: x = position || 0; y = -offset; s = Math.max(minExtent, Math.min(maxExtent, -bounds.y1)); if (title) { if (title.auto) { s += titlePadding; title.y = -s; s += title.bounds.height(); bounds.add(title.bounds.x1, 0) .add(title.bounds.x2, 0); } else { bounds.union(title.bounds); } } bounds.add(0, -s).add(range$$1, 0); break; case Left: x = -offset; y = position || 0; s = Math.max(minExtent, Math.min(maxExtent, -bounds.x1)); if (title) { if (title.auto) { s += titlePadding; title.x = -s; s += title.bounds.width(); bounds.add(0, title.bounds.y1) .add(0, title.bounds.y2); } else { bounds.union(title.bounds); } } bounds.add(-s, 0).add(0, range$$1); break; case Right: x = width + offset; y = position || 0; s = Math.max(minExtent, Math.min(maxExtent, bounds.x2)); if (title) { if (title.auto) { s += titlePadding; title.x = s; s += title.bounds.width(); bounds.add(0, title.bounds.y1) .add(0, title.bounds.y2); } else { bounds.union(title.bounds); } } bounds.add(0, 0).add(s, range$$1); break; case Bottom: x = position || 0; y = height + offset; s = Math.max(minExtent, Math.min(maxExtent, bounds.y2)); if (title) if (title.auto) { s += titlePadding; title.y = s; s += title.bounds.height(); bounds.add(title.bounds.x1, 0) .add(title.bounds.x2, 0); } else { bounds.union(title.bounds); } bounds.add(0, 0).add(range$$1, s); break; default: x = item.x; y = item.y; } // update bounds boundStroke(bounds.translate(x, y), item); if (set(item, 'x', x + AxisOffset) | set(item, 'y', y + AxisOffset)) { item.bounds = tempBounds$2; view.dirty(item); item.bounds = bounds; view.dirty(item); } return item.mark.bounds.clear().union(bounds); } function layoutTitle(view, title, axisBounds) { var item = title.items[0], datum = item.datum, orient = datum.orient, offset = item.offset, bounds = item.bounds, x = 0, y = 0; tempBounds$2.clear().union(bounds); // position axis group and title switch (orient) { case Top: x = item.x; y = axisBounds.y1 - offset; break; case Left: x = axisBounds.x1 - offset; y = item.y; break; case Right: x = axisBounds.x2 + offset; y = item.y; break; case Bottom: x = item.x; y = axisBounds.y2 + offset; break; default: x = item.x; y = item.y; } bounds.translate(x - item.x, y - item.y); if (set(item, 'x', x) | set(item, 'y', y)) { item.bounds = tempBounds$2; view.dirty(item); item.bounds = bounds; view.dirty(item); } // update bounds return title.bounds.clear().union(bounds); } function layoutLegend(view, legend, flow, xBounds, yBounds, width, height) { var item = legend.items[0], datum = item.datum, orient = datum.orient, offset = item.offset, bounds = item.bounds, x = 0, y = 0, w, h, axisBounds; if (orient === Top || orient === Bottom) { axisBounds = yBounds, x = flow[orient]; } else if (orient === Left || orient === Right) { axisBounds = xBounds; y = flow[orient]; } tempBounds$2.clear().union(bounds); bounds.clear(); // aggregate bounds to determine size // shave off 1 pixel because it looks better... item.items.forEach(function(_$$1) { bounds.union(_$$1.bounds); }); w = Math.round(bounds.width()) + 2 * item.padding - 1; h = Math.round(bounds.height()) + 2 * item.padding - 1; switch (orient) { case Left: x -= w + offset - Math.floor(axisBounds.x1); flow.left += h + flow.margin; break; case Right: x += offset + Math.ceil(axisBounds.x2); flow.right += h + flow.margin; break; case Top: y -= h + offset - Math.floor(axisBounds.y1); flow.top += w + flow.margin; break; case Bottom: y += offset + Math.ceil(axisBounds.y2); flow.bottom += w + flow.margin; break; case 'top-left': x += offset; y += offset; break; case 'top-right': x += width - w - offset; y += offset; break; case 'bottom-left': x += offset; y += height - h - offset; break; case 'bottom-right': x += width - w - offset; y += height - h - offset; break; default: x = item.x; y = item.y; } // update bounds boundStroke(bounds.set(x, y, x + w, y + h), item); // update legend layout if (set(item, 'x', x) | set(item, 'width', w) | set(item, 'y', y) | set(item, 'height', h)) { item.bounds = tempBounds$2; view.dirty(item); item.bounds = bounds; view.dirty(item); } return item.mark.bounds.clear().union(bounds); } function layoutSize(view, group, viewBounds, _$$1) { var auto = _$$1.autosize || {}, type = auto.type, viewWidth = view._width, viewHeight = view._height, padding = view.padding(); if (view._autosize < 1 || !type) return; var width = Math.max(0, group.width || 0), left = Math.max(0, Math.ceil(-viewBounds.x1)), right = Math.max(0, Math.ceil(viewBounds.x2 - width)), height = Math.max(0, group.height || 0), top = Math.max(0, Math.ceil(-viewBounds.y1)), bottom = Math.max(0, Math.ceil(viewBounds.y2 - height)); if (auto.contains === Padding) { viewWidth -= padding.left + padding.right; viewHeight -= padding.top + padding.bottom; } if (type === None$2) { left = 0; top = 0; width = viewWidth; height = viewHeight; } else if (type === Fit) { width = Math.max(0, viewWidth - left - right); height = Math.max(0, viewHeight - top - bottom); } else if (type === Pad) { viewWidth = width + left + right; viewHeight = height + top + bottom; } view._resizeView( viewWidth, viewHeight, width, height, [left, top], auto.resize ); } var vtx = Object.freeze({ bound: Bound, identifier: Identifier, mark: Mark, overlap: Overlap, render: Render, viewlayout: ViewLayout }); var Log = 'log'; var Pow = 'pow'; var Utc = 'utc'; var Sqrt = 'sqrt'; var Band = 'band'; var Time = 'time'; var Point = 'point'; var Linear = 'linear'; var Ordinal = 'ordinal'; var Quantile = 'quantile'; var Quantize = 'quantize'; var Threshold = 'threshold'; var BinLinear = 'bin-linear'; var BinOrdinal = 'bin-ordinal'; var Sequential = 'sequential'; var invertRange = function(scale) { return function(_$$1) { var lo = _$$1[0], hi = _$$1[1], t; if (hi < lo) { t = lo; lo = hi; hi = t; } return [ scale.invert(lo), scale.invert(hi) ]; } }; var invertRangeExtent = function(scale) { return function(_$$1) { var range$$1 = scale.range(), lo = _$$1[0], hi = _$$1[1], min$$1 = -1, max$$1, t, i, n; if (hi < lo) { t = lo; lo = hi; hi = t; } for (i=0, n=range$$1.length; i<n; ++i) { if (range$$1[i] >= lo && range$$1[i] <= hi) { if (min$$1 < 0) min$$1 = i; max$$1 = i; } } if (min$$1 < 0) return undefined; lo = scale.invertExtent(range$$1[min$$1]); hi = scale.invertExtent(range$$1[max$$1]); return [ lo[0] === undefined ? lo[1] : lo[0], hi[1] === undefined ? hi[0] : hi[1] ]; } }; var bandSpace = function(count, paddingInner, paddingOuter) { var space = count - paddingInner + paddingOuter * 2; return count ? (space > 0 ? space : 1) : 0; }; function band() { var scale = $.scaleOrdinal().unknown(undefined), domain = scale.domain, ordinalRange = scale.range, range$$1 = [0, 1], step, bandwidth, round = false, paddingInner = 0, paddingOuter = 0, align = 0.5; delete scale.unknown; function rescale() { var n = domain().length, reverse = range$$1[1] < range$$1[0], start = range$$1[reverse - 0], stop = range$$1[1 - reverse], space = bandSpace(n, paddingInner, paddingOuter); step = (stop - start) / (space || 1); if (round) { step = Math.floor(step); } start += (stop - start - step * (n - paddingInner)) * align; bandwidth = step * (1 - paddingInner); if (round) { start = Math.round(start); bandwidth = Math.round(bandwidth); } var values = d3Array.range(n).map(function(i) { return start + step * i; }); return ordinalRange(reverse ? values.reverse() : values); } scale.domain = function(_$$1) { if (arguments.length) { domain(_$$1); return rescale(); } else { return domain(); } }; scale.range = function(_$$1) { if (arguments.length) { range$$1 = [+_$$1[0], +_$$1[1]]; return rescale(); } else { return range$$1.slice(); } }; scale.rangeRound = function(_$$1) { range$$1 = [+_$$1[0], +_$$1[1]]; round = true; return rescale(); }; scale.bandwidth = function() { return bandwidth; }; scale.step = function() { return step; }; scale.round = function(_$$1) { if (arguments.length) { round = !!_$$1; return rescale(); } else { return round; } }; scale.padding = function(_$$1) { if (arguments.length) { paddingOuter = Math.max(0, Math.min(1, _$$1)); paddingInner = paddingOuter; return rescale(); } else { return paddingInner; } }; scale.paddingInner = function(_$$1) { if (arguments.length) { paddingInner = Math.max(0, Math.min(1, _$$1)); return rescale(); } else { return paddingInner; } }; scale.paddingOuter = function(_$$1) { if (arguments.length) { paddingOuter = Math.max(0, Math.min(1, _$$1)); return rescale(); } else { return paddingOuter; } }; scale.align = function(_$$1) { if (arguments.length) { align = Math.max(0, Math.min(1, _$$1)); return rescale(); } else { return align; } }; scale.invertRange = function(_$$1) { // bail if range has null or undefined values if (_$$1[0] == null || _$$1[1] == null) return; var lo = +_$$1[0], hi = +_$$1[1], reverse = range$$1[1] < range$$1[0], values = reverse ? ordinalRange().reverse() : ordinalRange(), n = values.length - 1, a, b, t; // bail if either range endpoint is invalid if (lo !== lo || hi !== hi) return; // order range inputs, bail if outside of scale range if (hi < lo) { t = lo; lo = hi; hi = t; } if (hi < values[0] || lo > range$$1[1-reverse]) return; // binary search to index into scale range a = Math.max(0, d3Array.bisectRight(values, lo) - 1); b = lo===hi ? a : d3Array.bisectRight(values, hi) - 1; // increment index a if lo is within padding gap if (lo - values[a] > bandwidth + 1e-10) ++a; if (reverse) { // map + swap t = a; a = n - b; b = n - t; } return (a > b) ? undefined : domain().slice(a, b+1); }; scale.invert = function(_$$1) { var value = scale.invertRange([_$$1, _$$1]); return value ? value[0] : value; }; scale.copy = function() { return band() .domain(domain()) .range(range$$1) .round(round) .paddingInner(paddingInner) .paddingOuter(paddingOuter) .align(align); }; return rescale(); } function pointish(scale) { var copy = scale.copy; scale.padding = scale.paddingOuter; delete scale.paddingInner; scale.copy = function() { return pointish(copy()); }; return scale; } function point$1() { return pointish(band().paddingInner(1)); } var map = Array.prototype.map; var slice = Array.prototype.slice; function numbers$1(_$$1) { return map.call(_$$1, function(x) { return +x; }); } function binLinear() { var linear = $.scaleLinear(), domain = []; function scale(x) { return linear(x); } function setDomain(_$$1) { domain = numbers$1(_$$1); linear.domain([domain[0], peek(domain)]); } scale.domain = function(_$$1) { return arguments.length ? (setDomain(_$$1), scale) : domain.slice(); }; scale.range = function(_$$1) { return arguments.length ? (linear.range(_$$1), scale) : linear.range(); }; scale.rangeRound = function(_$$1) { return arguments.length ? (linear.rangeRound(_$$1), scale) : linear.rangeRound(); }; scale.interpolate = function(_$$1) { return arguments.length ? (linear.interpolate(_$$1), scale) : linear.interpolate(); }; scale.invert = function(_$$1) { return linear.invert(_$$1); }; scale.ticks = function(count) { var n = domain.length, stride = ~~(n / (count || n)); return stride < 2 ? scale.domain() : domain.filter(function(x, i) { return !(i % stride); }); }; scale.tickFormat = function() { return linear.tickFormat.apply(linear, arguments); }; scale.copy = function() { return binLinear().domain(scale.domain()).range(scale.range()); }; return scale; } function binOrdinal() { var domain = [], range$$1 = []; function scale(x) { return x == null || x !== x ? undefined : range$$1[(d3Array.bisect(domain, x) - 1) % range$$1.length]; } scale.domain = function(_$$1) { if (arguments.length) { domain = numbers$1(_$$1); return scale; } else { return domain.slice(); } }; scale.range = function(_$$1) { if (arguments.length) { range$$1 = slice.call(_$$1); return scale; } else { return range$$1.slice(); } }; scale.copy = function() { return binOrdinal().domain(scale.domain()).range(scale.range()); }; return scale; } function sequential(interpolator) { var linear = $.scaleLinear(), x0 = 0, dx = 1, clamp = false; function update() { var domain = linear.domain(); x0 = domain[0]; dx = peek(domain) - x0; } function scale(x) { var t = (x - x0) / dx; return interpolator(clamp ? Math.max(0, Math.min(1, t)) : t); } scale.clamp = function(_$$1) { if (arguments.length) { clamp = !!_$$1; return scale; } else { return clamp; } }; scale.domain = function(_$$1) { return arguments.length ? (linear.domain(_$$1), update(), scale) : linear.domain(); }; scale.interpolator = function(_$$1) { if (arguments.length) { interpolator = _$$1; return scale; } else { return interpolator; } }; scale.copy = function() { return sequential().domain(linear.domain()).clamp(clamp).interpolator(interpolator); }; scale.ticks = function(count) { return linear.ticks(count); }; scale.tickFormat = function(count, specifier) { return linear.tickFormat(count, specifier); }; scale.nice = function(count) { return linear.nice(count), update(), scale; }; return scale; } /** * Augment scales with their type and needed inverse methods. */ function create(type, constructor) { return function scale() { var s = constructor(); if (!s.invertRange) { s.invertRange = s.invert ? invertRange(s) : s.invertExtent ? invertRangeExtent(s) : undefined; } s.type = type; return s; }; } function scale$1(type, scale) { if (arguments.length > 1) { scales[type] = create(type, scale); return this; } else { return scales.hasOwnProperty(type) ? scales[type] : undefined; } } var scales = { // base scale types identity: $.scaleIdentity, linear: $.scaleLinear, log: $.scaleLog, ordinal: $.scaleOrdinal, pow: $.scalePow, sqrt: $.scaleSqrt, quantile: $.scaleQuantile, quantize: $.scaleQuantize, threshold: $.scaleThreshold, time: $.scaleTime, utc: $.scaleUtc, // extended scale types band: band, point: point$1, sequential: sequential, 'bin-linear': binLinear, 'bin-ordinal': binOrdinal }; for (var key$1 in scales) { scale$1(key$1, scales[key$1]); } function colors(specifier) { var n = specifier.length / 6 | 0, colors = new Array(n), i = 0; while (i < n) colors[i] = "#" + specifier.slice(i * 6, ++i * 6); return colors; } var tableau10 = colors( '4c78a8f58518e4575672b7b254a24beeca3bb279a2ff9da69d755dbab0ac' ); var tableau20 = colors( '4c78a89ecae9f58518ffbf7954a24b88d27ab79a20f2cf5b43989483bcb6e45756ff9d9879706ebab0acd67195fcbfd2b279a2d6a5c99e765fd8b5a5' ); var blueOrange = new Array(3).concat( "67a9cff7f7f7f1a340", "0571b092c5defdb863e66101", "0571b092c5def7f7f7fdb863e66101", "2166ac67a9cfd1e5f0fee0b6f1a340b35806", "2166ac67a9cfd1e5f0f7f7f7fee0b6f1a340b35806", "2166ac4393c392c5ded1e5f0fee0b6fdb863e08214b35806", "2166ac4393c392c5ded1e5f0f7f7f7fee0b6fdb863e08214b35806", "0530612166ac4393c392c5ded1e5f0fee0b6fdb863e08214b358067f3b08", "0530612166ac4393c392c5ded1e5f0f7f7f7fee0b6fdb863e08214b358067f3b08" ).map(colors); var discrete = { blueorange: blueOrange }; var schemes = { // d3 built-in categorical palettes category10: $.schemeCategory10, category20: $.schemeCategory20, category20b: $.schemeCategory20b, category20c: $.schemeCategory20c, // extended categorical palettes accent: _.schemeAccent, dark2: _.schemeDark2, paired: _.schemePaired, pastel1: _.schemePastel1, pastel2: _.schemePastel2, set1: _.schemeSet1, set2: _.schemeSet2, set3: _.schemeSet3, tableau10: tableau10, tableau20: tableau20, // d3 built-in interpolators viridis: $.interpolateViridis, magma: $.interpolateMagma, inferno: $.interpolateInferno, plasma: $.interpolatePlasma, // extended interpolators blueorange: $$1.interpolateRgbBasis(peek(blueOrange)) }; function add$2(name, suffix) { schemes[name] = _['interpolate' + suffix]; discrete[name] = _['scheme' + suffix]; } // sequential single-hue add$2('blues', 'Blues'); add$2('greens', 'Greens'); add$2('greys', 'Greys'); add$2('purples', 'Purples'); add$2('reds', 'Reds'); add$2('oranges', 'Oranges'); // diverging add$2('brownbluegreen', 'BrBG'); add$2('purplegreen', 'PRGn'); add$2('pinkyellowgreen', 'PiYG'); add$2('purpleorange', 'PuOr'); add$2('redblue', 'RdBu'); add$2('redgrey', 'RdGy'); add$2('redyellowblue', 'RdYlBu'); add$2('redyellowgreen', 'RdYlGn'); add$2('spectral', 'Spectral'); // sequential multi-hue add$2('bluegreen', 'BuGn'); add$2('bluepurple', 'BuPu'); add$2('greenblue', 'GnBu'); add$2('orangered', 'OrRd'); add$2('purplebluegreen', 'PuBuGn'); add$2('purpleblue', 'PuBu'); add$2('purplered', 'PuRd'); add$2('redpurple', 'RdPu'); add$2('yellowgreenblue', 'YlGnBu'); add$2('yellowgreen', 'YlGn'); add$2('yelloworangebrown', 'YlOrBr'); add$2('yelloworangered', 'YlOrRd'); var getScheme = function(name, scheme) { if (arguments.length > 1) { schemes[name] = scheme; return this; } var part = name.split('-'); name = part[0]; part = +part[1] + 1; return part && discrete.hasOwnProperty(name) ? discrete[name][part-1] : !part && schemes.hasOwnProperty(name) ? schemes[name] : undefined; }; function interpolateRange(interpolator, range$$1) { var start = range$$1[0], span = peek(range$$1) - start; return function(i) { return interpolator(start + i * span); }; } function scaleFraction(scale, min$$1, max$$1) { var delta = max$$1 - min$$1; return !delta ? constant(0) : scale.type === 'linear' || scale.type === 'sequential' ? function(_$$1) { return (_$$1 - min$$1) / delta; } : scale.copy().domain([min$$1, max$$1]).range([0, 1]).interpolate(lerp); } function lerp(a, b) { var span = b - a; return function(i) { return a + i * span; } } function interpolate$1(type, gamma) { var interp = $$1[method(type)]; return (gamma != null && interp && interp.gamma) ? interp.gamma(gamma) : interp; } function method(type) { return 'interpolate' + type.toLowerCase() .split('-') .map(function(s) { return s[0].toUpperCase() + s.slice(1); }) .join(''); } var time = { millisecond: d3Time.timeMillisecond, second: d3Time.timeSecond, minute: d3Time.timeMinute, hour: d3Time.timeHour, day: d3Time.timeDay, week: d3Time.timeWeek, month: d3Time.timeMonth, year: d3Time.timeYear }; var utc = { millisecond: d3Time.utcMillisecond, second: d3Time.utcSecond, minute: d3Time.utcMinute, hour: d3Time.utcHour, day: d3Time.utcDay, week: d3Time.utcWeek, month: d3Time.utcMonth, year: d3Time.utcYear }; function timeInterval(name) { return time.hasOwnProperty(name) && time[name]; } function utcInterval(name) { return utc.hasOwnProperty(name) && utc[name]; } /** * Determine the tick count or interval function. * @param {Scale} scale - The scale for which to generate tick values. * @param {*} count - The desired tick count or interval specifier. * @return {*} - The tick count or interval function. */ function tickCount(scale$$1, count) { var step; if (isObject(count)) { step = count.step; count = count.interval; } if (isString(count)) { count = scale$$1.type === 'time' ? timeInterval(count) : scale$$1.type === 'utc' ? utcInterval(count) : error$1('Only time and utc scales accept interval strings.'); if (step) count = count.every(step); } return count; } /** * Filter a set of candidate tick values, ensuring that only tick values * that lie within the scale range are included. * @param {Scale} scale - The scale for which to generate tick values. * @param {Array<*>} ticks - The candidate tick values. * @param {*} count - The tick count or interval function. * @return {Array<*>} - The filtered tick values. */ function validTicks(scale$$1, ticks, count) { var range$$1 = scale$$1.range(), lo = range$$1[0], hi = peek(range$$1); if (lo > hi) { range$$1 = hi; hi = lo; lo = range$$1; } ticks = ticks.filter(function(v) { v = scale$$1(v); return !(v < lo || v > hi) }); if (count > 0 && ticks.length > 1) { var endpoints = [ticks[0], peek(ticks)]; while (ticks.length > count && ticks.length >= 3) { ticks = ticks.filter(function(_$$1, i) { return !(i % 2); }); } if (ticks.length < 3) { ticks = endpoints; } } return ticks; } /** * Generate tick values for the given scale and approximate tick count or * interval value. If the scale has a 'ticks' method, it will be used to * generate the ticks, with the count argument passed as a parameter. If the * scale lacks a 'ticks' method, the full scale domain will be returned. * @param {Scale} scale - The scale for which to generate tick values. * @param {*} [count] - The approximate number of desired ticks. * @return {Array<*>} - The generated tick values. */ function tickValues(scale$$1, count) { return scale$$1.ticks ? scale$$1.ticks(count) : scale$$1.domain(); } /** * Generate a label format function for a scale. If the scale has a * 'tickFormat' method, it will be used to generate the formatter, with the * count and specifier arguments passed as parameters. If the scale lacks a * 'tickFormat' method, the returned formatter performs simple string coercion. * If the input scale is a logarithmic scale and the format specifier does not * indicate a desired decimal precision, a special variable precision formatter * that automatically trims trailing zeroes will be generated. * @param {Scale} scale - The scale for which to generate the label formatter. * @param {*} [count] - The approximate number of desired ticks. * @param {string} [specifier] - The format specifier. Must be a legal d3 4.0 * specifier string (see https://github.com/d3/d3-format#formatSpecifier). * @return {function(*):string} - The generated label formatter. */ function tickFormat(scale$$1, count, specifier) { var format$$1 = scale$$1.tickFormat ? scale$$1.tickFormat(count, specifier) : String; return (scale$$1.type === Log) ? filter$1(format$$1, variablePrecision(specifier)) : format$$1; } function filter$1(sourceFormat, targetFormat) { return function(_$$1) { return sourceFormat(_$$1) ? targetFormat(_$$1) : ''; }; } function variablePrecision(specifier) { var s = d3Format.formatSpecifier(specifier || ','); if (s.precision == null) { s.precision = 12; switch (s.type) { case '%': s.precision -= 2; break; case 'e': s.precision -= 1; break; } return trimZeroes( d3Format.format(s), // number format d3Format.format('.1f')(1)[1] // decimal point character ); } else { return d3Format.format(s); } } function trimZeroes(format$$1, decimalChar) { return function(x) { var str = format$$1(x), dec = str.indexOf(decimalChar), idx, end; if (dec < 0) return str; idx = rightmostDigit(str, dec); end = idx < str.length ? str.slice(idx) : ''; while (--idx > dec) if (str[idx] !== '0') { ++idx; break; } return str.slice(0, idx) + end; }; } function rightmostDigit(str, dec) { var i = str.lastIndexOf('e'), c; if (i > 0) return i; for (i=str.length; --i > dec;) { c = str.charCodeAt(i); if (c >= 48 && c <= 57) return i + 1; // is digit } } /** * Generates axis ticks for visualizing a spatial scale. * @constructor * @param {object} params - The parameters for this operator. * @param {Scale} params.scale - The scale to generate ticks for. * @param {*} [params.count=10] - The approximate number of ticks, or * desired tick interval, to use. * @param {Array<*>} [params.values] - The exact tick values to use. * These must be legal domain values for the provided scale. * If provided, the count argument is ignored. * @param {function(*):string} [params.formatSpecifier] - A format specifier * to use in conjunction with scale.tickFormat. Legal values are * any valid d3 4.0 format specifier. * @param {function(*):string} [params.format] - The format function to use. * If provided, the formatSpecifier argument is ignored. */ function AxisTicks(params) { Transform.call(this, null, params); } var prototype$52 = inherits(AxisTicks, Transform); prototype$52.transform = function(_$$1, pulse) { if (this.value && !_$$1.modified()) { return pulse.StopPropagation; } var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), ticks = this.value, scale = _$$1.scale, count = _$$1.count == null ? (_$$1.values ? _$$1.values.length : 10) : tickCount(scale, _$$1.count), format$$1 = _$$1.format || tickFormat(scale, count, _$$1.formatSpecifier), values = _$$1.values ? validTicks(scale, _$$1.values, count) : tickValues(scale, count); if (ticks) out.rem = ticks; ticks = values.map(function(value, i) { return ingest({ index: i / (values.length - 1), value: value, label: format$$1(value) }); }); if (_$$1.extra) { // add an extra tick pegged to the initial domain value // this is used to generate axes with 'binned' domains ticks.push(ingest({ index: -1, extra: {value: ticks[0].value}, label: '' })); } out.source = ticks; out.add = ticks; this.value = ticks; return out; }; /** * Joins a set of data elements against a set of visual items. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): object} [params.item] - An item generator function. * @param {function(object): *} [params.key] - The key field associating data and visual items. */ function DataJoin(params) { Transform.call(this, null, params); } var prototype$53 = inherits(DataJoin, Transform); function defaultItemCreate() { return ingest({}); } function isExit(t) { return t.exit; } prototype$53.transform = function(_$$1, pulse) { var df = pulse.dataflow, out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), item = _$$1.item || defaultItemCreate, key$$1 = _$$1.key || tupleid, map = this.value; // prevent transient (e.g., hover) requests from // cascading across marks derived from marks if (isArray(out.encode)) { out.encode = null; } if (map && (_$$1.modified('key') || pulse.modified(key$$1))) { error$1('DataJoin does not support modified key function or fields.'); } if (!map) { pulse = pulse.addAll(); this.value = map = fastmap().test(isExit); map.lookup = function(t) { return map.get(key$$1(t)); }; } pulse.visit(pulse.ADD, function(t) { var k = key$$1(t), x = map.get(k); if (x) { if (x.exit) { map.empty--; out.add.push(x); } else { out.mod.push(x); } } else { map.set(k, (x = item(t))); out.add.push(x); } x.datum = t; x.exit = false; }); pulse.visit(pulse.MOD, function(t) { var k = key$$1(t), x = map.get(k); if (x) { x.datum = t; out.mod.push(x); } }); pulse.visit(pulse.REM, function(t) { var k = key$$1(t), x = map.get(k); if (t === x.datum && !x.exit) { out.rem.push(x); x.exit = true; ++map.empty; } }); if (pulse.changed(pulse.ADD_MOD)) out.modifies('datum'); if (_$$1.clean && map.empty > df.cleanThreshold) df.runAfter(map.clean); return out; }; /** * Invokes encoding functions for visual items. * @constructor * @param {object} params - The parameters to the encoding functions. This * parameter object will be passed through to all invoked encoding functions. * @param {object} param.encoders - The encoding functions * @param {function(object, object): boolean} [param.encoders.update] - Update encoding set * @param {function(object, object): boolean} [param.encoders.enter] - Enter encoding set * @param {function(object, object): boolean} [param.encoders.exit] - Exit encoding set */ function Encode(params) { Transform.call(this, null, params); } var prototype$54 = inherits(Encode, Transform); prototype$54.transform = function(_$$1, pulse) { var out = pulse.fork(pulse.ADD_REM), encoders = _$$1.encoders, encode = pulse.encode; // if an array, the encode directive includes additional sets // that must be defined in order for the primary set to be invoked // e.g., only run the update set if the hover set is defined if (isArray(encode)) { if (out.changed() || encode.every(function(e) { return encoders[e]; })) { encode = encode[0]; } else { return pulse.StopPropagation; } } // marshall encoder functions var reenter = encode === 'enter', update = encoders.update || falsy, enter = encoders.enter || falsy, exit = encoders.exit || falsy, set = (encode && !reenter ? encoders[encode] : update) || falsy; if (pulse.changed(pulse.ADD)) { pulse.visit(pulse.ADD, function(t) { enter(t, _$$1); update(t, _$$1); if (set !== falsy && set !== update) set(t, _$$1); }); out.modifies(enter.output); out.modifies(update.output); if (set !== falsy && set !== update) out.modifies(set.output); } if (pulse.changed(pulse.REM) && exit !== falsy) { pulse.visit(pulse.REM, function(t) { exit(t, _$$1); }); out.modifies(exit.output); } if (reenter || set !== falsy) { var flag = pulse.MOD | (_$$1.modified() ? pulse.REFLOW : 0); if (reenter) { pulse.visit(flag, function(t) { var mod = enter(t, _$$1); if (set(t, _$$1) || mod) out.mod.push(t); }); if (out.mod.length) out.modifies(enter.output); } else { pulse.visit(flag, function(t) { if (set(t, _$$1)) out.mod.push(t); }); } if (out.mod.length) out.modifies(set.output); } return out.changed() ? out : pulse.StopPropagation; }; var discrete$1 = {}; discrete$1[Quantile] = quantile$1; discrete$1[Quantize] = quantize$1; discrete$1[Threshold] = threshold; discrete$1[BinLinear] = bin$1; discrete$1[BinOrdinal] = bin$1; function labelValues(scale, count, gradient) { if (gradient) return scale.domain(); var values = discrete$1[scale.type]; return values ? values(scale) : tickValues(scale, count); } function quantize$1(scale) { var domain = scale.domain(), x0 = domain[0], x1 = peek(domain), n = scale.range().length, values = new Array(n), i = 0; values[0] = -Infinity; while (++i < n) values[i] = (i * x1 - (i - n) * x0) / n; values.max = +Infinity; return values; } function quantile$1(scale) { var values = [-Infinity].concat(scale.quantiles()); values.max = +Infinity; return values; } function threshold(scale) { var values = [-Infinity].concat(scale.domain()); values.max = +Infinity; return values; } function bin$1(scale) { var values = scale.domain(); values.max = values.pop(); return values; } function labelFormat(scale, format$$1) { return discrete$1[scale.type] ? formatRange(format$$1) : formatPoint(format$$1); } function formatRange(format$$1) { return function(value, index, array$$1) { var limit = array$$1[index + 1] || array$$1.max || +Infinity, lo = formatValue(value, format$$1), hi = formatValue(limit, format$$1); return lo && hi ? lo + '\u2013' + hi : hi ? '< ' + hi : '\u2265 ' + lo; }; } function formatValue(value, format$$1) { return isFinite(value) ? format$$1(value) : null; } function formatPoint(format$$1) { return function(value) { return format$$1(value); }; } /** * Generates legend entries for visualizing a scale. * @constructor * @param {object} params - The parameters for this operator. * @param {Scale} params.scale - The scale to generate items for. * @param {*} [params.count=10] - The approximate number of items, or * desired tick interval, to use. * @param {Array<*>} [params.values] - The exact tick values to use. * These must be legal domain values for the provided scale. * If provided, the count argument is ignored. * @param {function(*):string} [params.formatSpecifier] - A format specifier * to use in conjunction with scale.tickFormat. Legal values are * any valid d3 4.0 format specifier. * @param {function(*):string} [params.format] - The format function to use. * If provided, the formatSpecifier argument is ignored. */ function LegendEntries(params) { Transform.call(this, [], params); } var prototype$55 = inherits(LegendEntries, Transform); prototype$55.transform = function(_$$1, pulse) { if (this.value != null && !_$$1.modified()) { return pulse.StopPropagation; } var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), total = 0, items = this.value, grad = _$$1.type === 'gradient', scale = _$$1.scale, count = _$$1.count == null ? 5 : tickCount(scale, _$$1.count), format$$1 = _$$1.format || tickFormat(scale, count, _$$1.formatSpecifier), values = _$$1.values || labelValues(scale, count, grad); format$$1 = labelFormat(scale, format$$1); if (items) out.rem = items; if (grad) { var domain = _$$1.values ? scale.domain() : values, fraction = scaleFraction(scale, domain[0], peek(domain)); } else { var size = _$$1.size, offset; if (isFunction(size)) { // if first value maps to size zero, remove from list (vega#717) if (!_$$1.values && scale(values[0]) === 0) { values = values.slice(1); } // compute size offset for legend entries offset = values.reduce(function(max$$1, value) { return Math.max(max$$1, size(value, _$$1)); }, 0); } else { size = constant(offset = size || 8); } } items = values.map(function(value, index) { var t = ingest({ index: index, label: format$$1(value, index, values), value: value }); if (grad) { t.perc = fraction(value); } else { t.offset = offset; t.size = size(value, _$$1); t.total = Math.round(total); total += t.size; } return t; }); out.source = items; out.add = items; this.value = items; return out; }; var Paths = fastmap({ 'line': line$3, 'line-radial': lineR, 'arc': arc$3, 'arc-radial': arcR, 'curve': curve, 'curve-radial': curveR, 'orthogonal-horizontal': orthoX, 'orthogonal-vertical': orthoY, 'orthogonal-radial': orthoR, 'diagonal-horizontal': diagonalX, 'diagonal-vertical': diagonalY, 'diagonal-radial': diagonalR }); function sourceX(t) { return t.source.x; } function sourceY(t) { return t.source.y; } function targetX(t) { return t.target.x; } function targetY(t) { return t.target.y; } /** * Layout paths linking source and target elements. * @constructor * @param {object} params - The parameters for this operator. */ function LinkPath(params) { Transform.call(this, {}, params); } LinkPath.Definition = { "type": "LinkPath", "metadata": {"modifies": true}, "params": [ { "name": "sourceX", "type": "field", "default": "source.x" }, { "name": "sourceY", "type": "field", "default": "source.y" }, { "name": "targetX", "type": "field", "default": "target.x" }, { "name": "targetY", "type": "field", "default": "target.y" }, { "name": "orient", "type": "enum", "default": "vertical", "values": ["horizontal", "vertical", "radial"] }, { "name": "shape", "type": "enum", "default": "line", "values": ["line", "arc", "curve", "diagonal", "orthogonal"] }, { "name": "as", "type": "string", "default": "path" } ] }; var prototype$56 = inherits(LinkPath, Transform); prototype$56.transform = function(_$$1, pulse) { var sx = _$$1.sourceX || sourceX, sy = _$$1.sourceY || sourceY, tx = _$$1.targetX || targetX, ty = _$$1.targetY || targetY, as = _$$1.as || 'path', orient = _$$1.orient || 'vertical', shape = _$$1.shape || 'line', path$$1 = Paths.get(shape + '-' + orient) || Paths.get(shape); if (!path$$1) { error$1('LinkPath unsupported type: ' + _$$1.shape + (_$$1.orient ? '-' + _$$1.orient : '')); } pulse.visit(pulse.SOURCE, function(t) { t[as] = path$$1(sx(t), sy(t), tx(t), ty(t)); }); return pulse.reflow(_$$1.modified()).modifies(as); }; // -- Link Path Generation Methods ----- function line$3(sx, sy, tx, ty) { return 'M' + sx + ',' + sy + 'L' + tx + ',' + ty; } function lineR(sa, sr, ta, tr) { return line$3( sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta) ); } function arc$3(sx, sy, tx, ty) { var dx = tx - sx, dy = ty - sy, rr = Math.sqrt(dx * dx + dy * dy) / 2, ra = 180 * Math.atan2(dy, dx) / Math.PI; return 'M' + sx + ',' + sy + 'A' + rr + ',' + rr + ' ' + ra + ' 0 1' + ' ' + tx + ',' + ty; } function arcR(sa, sr, ta, tr) { return arc$3( sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta) ); } function curve(sx, sy, tx, ty) { var dx = tx - sx, dy = ty - sy, ix = 0.2 * (dx + dy), iy = 0.2 * (dy - dx); return 'M' + sx + ',' + sy + 'C' + (sx+ix) + ',' + (sy+iy) + ' ' + (tx+iy) + ',' + (ty-ix) + ' ' + tx + ',' + ty; } function curveR(sa, sr, ta, tr) { return curve( sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta) ); } function orthoX(sx, sy, tx, ty) { return 'M' + sx + ',' + sy + 'V' + ty + 'H' + tx; } function orthoY(sx, sy, tx, ty) { return 'M' + sx + ',' + sy + 'H' + tx + 'V' + ty; } function orthoR(sa, sr, ta, tr) { var sc = Math.cos(sa), ss = Math.sin(sa), tc = Math.cos(ta), ts = Math.sin(ta), sf = Math.abs(ta - sa) > Math.PI ? ta <= sa : ta > sa; return 'M' + (sr*sc) + ',' + (sr*ss) + 'A' + sr + ',' + sr + ' 0 0,' + (sf?1:0) + ' ' + (sr*tc) + ',' + (sr*ts) + 'L' + (tr*tc) + ',' + (tr*ts); } function diagonalX(sx, sy, tx, ty) { var m = (sx + tx) / 2; return 'M' + sx + ',' + sy + 'C' + m + ',' + sy + ' ' + m + ',' + ty + ' ' + tx + ',' + ty; } function diagonalY(sx, sy, tx, ty) { var m = (sy + ty) / 2; return 'M' + sx + ',' + sy + 'C' + sx + ',' + m + ' ' + tx + ',' + m + ' ' + tx + ',' + ty; } function diagonalR(sa, sr, ta, tr) { var sc = Math.cos(sa), ss = Math.sin(sa), tc = Math.cos(ta), ts = Math.sin(ta), mr = (sr + tr) / 2; return 'M' + (sr*sc) + ',' + (sr*ss) + 'C' + (mr*sc) + ',' + (mr*ss) + ' ' + (mr*tc) + ',' + (mr*ts) + ' ' + (tr*tc) + ',' + (tr*ts); } /** * Pie and donut chart layout. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to size pie segments. * @param {number} [params.startAngle=0] - The start angle (in radians) of the layout. * @param {number} [params.endAngle=2π] - The end angle (in radians) of the layout. * @param {boolean} [params.sort] - Boolean flag for sorting sectors by value. */ function Pie(params) { Transform.call(this, null, params); } Pie.Definition = { "type": "Pie", "metadata": {"modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "startAngle", "type": "number", "default": 0 }, { "name": "endAngle", "type": "number", "default": 6.283185307179586 }, { "name": "sort", "type": "boolean", "default": false }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["startAngle", "endAngle"] } ] }; var prototype$57 = inherits(Pie, Transform); prototype$57.transform = function(_$$1, pulse) { var as = _$$1.as || ['startAngle', 'endAngle'], startAngle = as[0], endAngle = as[1], field$$1 = _$$1.field || one, start = _$$1.startAngle || 0, stop = _$$1.endAngle != null ? _$$1.endAngle : 2 * Math.PI, data = pulse.source, values = data.map(field$$1), n = values.length, a = start, k = (stop - start) / d3Array.sum(values), index = d3Array.range(n), i, t, v; if (_$$1.sort) { index.sort(function(a, b) { return values[a] - values[b]; }); } for (i=0; i<n; ++i) { v = values[index[i]]; t = data[index[i]]; t[startAngle] = a; t[endAngle] = (a += v * k); } this.value = values; return pulse.reflow(_$$1.modified()).modifies(as); }; var DEFAULT_COUNT = 5; var INCLUDE_ZERO = toSet([Linear, Pow, Sqrt]); var INCLUDE_PAD = toSet([Linear, Log, Pow, Sqrt, Time, Utc]); var SKIP$2 = toSet([ 'set', 'modified', 'clear', 'type', 'scheme', 'schemeExtent', 'schemeCount', 'domain', 'domainMin', 'domainMid', 'domainMax', 'domainRaw', 'nice', 'zero', 'range', 'rangeStep', 'round', 'reverse', 'interpolate', 'interpolateGamma' ]); /** * Maintains a scale function mapping data values to visual channels. * @constructor * @param {object} params - The parameters for this operator. */ function Scale(params) { Transform.call(this, null, params); this.modified(true); // always treat as modified } var prototype$58 = inherits(Scale, Transform); prototype$58.transform = function(_$$1, pulse) { var df = pulse.dataflow, scale = this.value, prop; if (!scale || _$$1.modified('type')) { this.value = scale = scale$1((_$$1.type || Linear).toLowerCase())(); } for (prop in _$$1) if (!SKIP$2[prop]) { // padding is a scale property for band/point but not others if (prop === 'padding' && INCLUDE_PAD[scale.type]) continue; // invoke scale property setter, raise warning if not found isFunction(scale[prop]) ? scale[prop](_$$1[prop]) : df.warn('Unsupported scale property: ' + prop); } configureRange(scale, _$$1, configureDomain(scale, _$$1, df)); return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); }; function configureDomain(scale, _$$1, df) { // check raw domain, if provided use that and exit early var raw = rawDomain(scale, _$$1.domainRaw); if (raw > -1) return raw; var domain = _$$1.domain, type = scale.type, zero$$1 = _$$1.zero || (_$$1.zero === undefined && INCLUDE_ZERO[type]), n, mid; if (!domain) return 0; // adjust continuous domain for minimum pixel padding if (INCLUDE_PAD[type] && _$$1.padding && domain[0] !== peek(domain)) { domain = padDomain(type, domain, _$$1.range, _$$1.padding, _$$1.exponent); } // adjust domain based on zero, min, max settings if (zero$$1 || _$$1.domainMin != null || _$$1.domainMax != null || _$$1.domainMid != null) { n = ((domain = domain.slice()).length - 1) || 1; if (zero$$1) { if (domain[0] > 0) domain[0] = 0; if (domain[n] < 0) domain[n] = 0; } if (_$$1.domainMin != null) domain[0] = _$$1.domainMin; if (_$$1.domainMax != null) domain[n] = _$$1.domainMax; if (_$$1.domainMid != null) { mid = _$$1.domainMid; if (mid < domain[0] || mid > domain[n]) { df.warn('Scale domainMid exceeds domain min or max.', mid); } domain.splice(n, 0, mid); } } // set the scale domain scale.domain(domain); // perform 'nice' adjustment as requested if (_$$1.nice && scale.nice) { scale.nice((_$$1.nice !== true && tickCount(scale, _$$1.nice)) || null); } // return the cardinality of the domain return domain.length; } function rawDomain(scale, raw) { if (raw) { scale.domain(raw); return raw.length; } else { return -1; } } function padDomain(type, domain, range$$1, pad$$1, exponent) { var span = Math.abs(peek(range$$1) - range$$1[0]), frac = span / (span - 2 * pad$$1), d = type === Log ? zoomLog(domain, null, frac) : type === Sqrt ? zoomPow(domain, null, frac, 0.5) : type === Pow ? zoomPow(domain, null, frac, exponent) : zoomLinear(domain, null, frac); domain = domain.slice(); domain[0] = d[0]; domain[domain.length-1] = d[1]; return domain; } function configureRange(scale, _$$1, count) { var round = _$$1.round || false, range$$1 = _$$1.range; // if range step specified, calculate full range extent if (_$$1.rangeStep != null) { range$$1 = configureRangeStep(scale.type, _$$1, count); } // else if a range scheme is defined, use that else if (_$$1.scheme) { range$$1 = configureScheme(scale.type, _$$1, count); if (isFunction(range$$1)) return scale.interpolator(range$$1); } // given a range array for a sequential scale, convert to interpolator else if (range$$1 && scale.type === Sequential) { return scale.interpolator($$1.interpolateRgbBasis(flip(range$$1, _$$1.reverse))); } // configure rounding / interpolation if (range$$1 && _$$1.interpolate && scale.interpolate) { scale.interpolate(interpolate$1(_$$1.interpolate, _$$1.interpolateGamma)); } else if (isFunction(scale.round)) { scale.round(round); } else if (isFunction(scale.rangeRound)) { scale.interpolate(round ? $$1.interpolateRound : $$1.interpolate); } if (range$$1) scale.range(flip(range$$1, _$$1.reverse)); } function configureRangeStep(type, _$$1, count) { if (type !== Band && type !== Point) { error$1('Only band and point scales support rangeStep.'); } // calculate full range based on requested step size and padding var outer = (_$$1.paddingOuter != null ? _$$1.paddingOuter : _$$1.padding) || 0, inner = type === Point ? 1 : ((_$$1.paddingInner != null ? _$$1.paddingInner : _$$1.padding) || 0); return [0, _$$1.rangeStep * bandSpace(count, inner, outer)]; } function configureScheme(type, _$$1, count) { var name = _$$1.scheme.toLowerCase(), scheme = getScheme(name), extent$$1 = _$$1.schemeExtent, discrete; if (!scheme) { error$1('Unrecognized scheme name: ' + _$$1.scheme); } // determine size for potential discrete range count = (type === Threshold) ? count + 1 : (type === BinOrdinal) ? count - 1 : (type === Quantile || type === Quantize) ? (+_$$1.schemeCount || DEFAULT_COUNT) : count; // adjust and/or quantize scheme as appropriate return type === Sequential ? adjustScheme(scheme, extent$$1, _$$1.reverse) : !extent$$1 && (discrete = getScheme(name + '-' + count)) ? discrete : isFunction(scheme) ? quantize$2(adjustScheme(scheme, extent$$1), count) : type === Ordinal ? scheme : scheme.slice(0, count); } function adjustScheme(scheme, extent$$1, reverse) { return (isFunction(scheme) && (extent$$1 || reverse)) ? interpolateRange(scheme, flip(extent$$1 || [0, 1], reverse)) : scheme; } function flip(array$$1, reverse) { return reverse ? array$$1.slice().reverse() : array$$1; } function quantize$2(interpolator, count) { var samples = new Array(count), n = (count - 1) || 1; for (var i = 0; i < count; ++i) samples[i] = interpolator(i / n); return samples; } /** * Sorts scenegraph items in the pulse source array. * @constructor * @param {object} params - The parameters for this operator. * @param {function(*,*): number} [params.sort] - A comparator * function for sorting tuples. */ function SortItems(params) { Transform.call(this, null, params); } var prototype$59 = inherits(SortItems, Transform); prototype$59.transform = function(_$$1, pulse) { var mod = _$$1.modified('sort') || pulse.changed(pulse.ADD) || pulse.modified(_$$1.sort.fields) || pulse.modified('datum'); if (mod) pulse.source.sort(_$$1.sort); this.modified(mod); return pulse; }; var Center = 'center'; var Normalize = 'normalize'; /** * Stack layout for visualization elements. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to stack. * @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby. * @param {function(object,object): number} [params.sort] - A comparator for stack sorting. * @param {string} [offset='zero'] - One of 'zero', 'center', 'normalize'. */ function Stack(params) { Transform.call(this, null, params); } Stack.Definition = { "type": "Stack", "metadata": {"modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "groupby", "type": "field", "array": true }, { "name": "sort", "type": "compare" }, { "name": "offset", "type": "enum", "default": "zero", "values": ["zero", "center", "normalize"] }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["y0", "y1"] } ] }; var prototype$60 = inherits(Stack, Transform); prototype$60.transform = function(_$$1, pulse) { var as = _$$1.as || ['y0', 'y1'], y0 = as[0], y1 = as[1], field$$1 = _$$1.field || one, stack = _$$1.offset === Center ? stackCenter : _$$1.offset === Normalize ? stackNormalize : stackZero, groups, i, n, max$$1; // partition, sum, and sort the stack groups groups = partition$2(pulse.source, _$$1.groupby, _$$1.sort, field$$1); // compute stack layouts per group for (i=0, n=groups.length, max$$1=groups.max; i<n; ++i) { stack(groups[i], max$$1, field$$1, y0, y1); } return pulse.reflow(_$$1.modified()).modifies(as); }; function stackCenter(group, max$$1, field$$1, y0, y1) { var last = (max$$1 - group.sum) / 2, m = group.length, j = 0, t; for (; j<m; ++j) { t = group[j]; t[y0] = last; t[y1] = (last += Math.abs(field$$1(t))); } } function stackNormalize(group, max$$1, field$$1, y0, y1) { var scale = 1 / group.sum, last = 0, m = group.length, j = 0, v = 0, t; for (; j<m; ++j) { t = group[j]; t[y0] = last; t[y1] = last = scale * (v += Math.abs(field$$1(t))); } } function stackZero(group, max$$1, field$$1, y0, y1) { var lastPos = 0, lastNeg = 0, m = group.length, j = 0, v, t; for (; j<m; ++j) { t = group[j]; v = field$$1(t); if (v < 0) { t[y0] = lastNeg; t[y1] = (lastNeg += v); } else { t[y0] = lastPos; t[y1] = (lastPos += v); } } } function partition$2(data, groupby, sort, field$$1) { var groups = [], get = function(f) { return f(t); }, map, i, n, m, t, k, g, s, max$$1; // partition data points into stack groups if (groupby == null) { groups.push(data.slice()); } else { for (map={}, i=0, n=data.length; i<n; ++i) { t = data[i]; k = groupby.map(get); g = map[k]; if (!g) { map[k] = (g = []); groups.push(g); } g.push(t); } } // compute sums of groups, sort groups as needed for (k=0, max$$1=0, m=groups.length; k<m; ++k) { g = groups[k]; for (i=0, s=0, n=g.length; i<n; ++i) { s += Math.abs(field$$1(g[i])); } g.sum = s; if (s > max$$1) max$$1 = s; if (sort) g.sort(sort); } groups.max = max$$1; return groups; } var encode = Object.freeze({ axisticks: AxisTicks, datajoin: DataJoin, encode: Encode, legendentries: LegendEntries, linkpath: LinkPath, pie: Pie, scale: Scale, sortitems: SortItems, stack: Stack, validTicks: validTicks }); var array$1 = Array.prototype; var slice$1 = array$1.slice; var ascending$1 = function(a, b) { return a - b; }; var area$3 = function(ring) { var i = 0, n = ring.length, area$$1 = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1]; while (++i < n) area$$1 += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1]; return area$$1; }; var constant$2 = function(x) { return function() { return x; }; }; var contains = function(ring, hole) { var i = -1, n = hole.length, c; while (++i < n) if (c = ringContains(ring, hole[i])) return c; return 0; }; function ringContains(ring, point) { var x = point[0], y = point[1], contains = -1; for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) { var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1]; if (segmentContains(pi, pj, point)) return 0; if (((yi > y) !== (yj > y)) && ((x < (xj - xi) * (y - yi) / (yj - yi) + xi))) contains = -contains; } return contains; } function segmentContains(a, b, c) { var i; return collinear(a, b, c) && within(a[i = +(a[0] === b[0])], c[i], b[i]); } function collinear(a, b, c) { return (b[0] - a[0]) * (c[1] - a[1]) === (c[0] - a[0]) * (b[1] - a[1]); } function within(p, q, r) { return p <= q && q <= r || r <= q && q <= p; } var noop$1 = function() {}; var cases = [ [], [[[1.0, 1.5], [0.5, 1.0]]], [[[1.5, 1.0], [1.0, 1.5]]], [[[1.5, 1.0], [0.5, 1.0]]], [[[1.0, 0.5], [1.5, 1.0]]], [[[1.0, 1.5], [0.5, 1.0]], [[1.0, 0.5], [1.5, 1.0]]], [[[1.0, 0.5], [1.0, 1.5]]], [[[1.0, 0.5], [0.5, 1.0]]], [[[0.5, 1.0], [1.0, 0.5]]], [[[1.0, 1.5], [1.0, 0.5]]], [[[0.5, 1.0], [1.0, 0.5]], [[1.5, 1.0], [1.0, 1.5]]], [[[1.5, 1.0], [1.0, 0.5]]], [[[0.5, 1.0], [1.5, 1.0]]], [[[1.0, 1.5], [1.5, 1.0]]], [[[0.5, 1.0], [1.0, 1.5]]], [] ]; var contours = function() { var dx = 1, dy = 1, threshold = d3Array.thresholdSturges, smooth = smoothLinear; function contours(values) { var tz = threshold(values); // Convert number of thresholds into uniform thresholds. if (!Array.isArray(tz)) { var domain = d3Array.extent(values), start = domain[0], stop = domain[1]; tz = d3Array.tickStep(start, stop, tz); tz = d3Array.range(Math.floor(start / tz) * tz, Math.floor(stop / tz) * tz, tz); } else { tz = tz.slice().sort(ascending$1); } // Accumulate, smooth contour rings, assign holes to exterior rings. // Based on https://github.com/mbostock/shapefile/blob/v0.6.2/shp/polygon.js var layers = tz.map(function(value) { var polygons = [], holes = []; isorings(values, value, function(ring) { smooth(ring, values, value); if (area$3(ring) > 0) polygons.push([ring]); else holes.push(ring); }); holes.forEach(function(hole) { for (var i = 0, n = polygons.length, polygon; i < n; ++i) { if (contains((polygon = polygons[i])[0], hole) !== -1) { polygon.push(hole); return; } } }); return polygons; }); return layers.map(function(polygons, i) { return { type: "MultiPolygon", value: tz[i], coordinates: polygons }; }); } // Marching squares with isolines stitched into rings. // Based on https://github.com/topojson/topojson-client/blob/v3.0.0/src/stitch.js function isorings(values, value, callback) { var fragmentByStart = new Array, fragmentByEnd = new Array, x, y, t0, t1, t2, t3; // Special case for the first row (y = -1, t2 = t3 = 0). x = y = -1; t1 = values[0] >= value; cases[t1 << 1].forEach(stitch); while (++x < dx - 1) { t0 = t1, t1 = values[x + 1] >= value; cases[t0 | t1 << 1].forEach(stitch); } cases[t1 << 0].forEach(stitch); // General case for the intermediate rows. while (++y < dy - 1) { x = -1; t1 = values[y * dx + dx] >= value; t2 = values[y * dx] >= value; cases[t1 << 1 | t2 << 2].forEach(stitch); while (++x < dx - 1) { t0 = t1, t1 = values[y * dx + dx + x + 1] >= value; t3 = t2, t2 = values[y * dx + x + 1] >= value; cases[t0 | t1 << 1 | t2 << 2 | t3 << 3].forEach(stitch); } cases[t1 | t2 << 3].forEach(stitch); } // Special case for the last row (y = dy - 1, t0 = t1 = 0). x = -1; t2 = values[y * dx] >= value; cases[t2 << 2].forEach(stitch); while (++x < dx - 1) { t3 = t2, t2 = values[y * dx + x + 1] >= value; cases[t2 << 2 | t3 << 3].forEach(stitch); } cases[t2 << 3].forEach(stitch); function stitch(line$$1) { var start = [line$$1[0][0] + x, line$$1[0][1] + y], end = [line$$1[1][0] + x, line$$1[1][1] + y], startIndex = index(start), endIndex = index(end), f, g; if (f = fragmentByEnd[startIndex]) { if (g = fragmentByStart[endIndex]) { delete fragmentByEnd[f.end]; delete fragmentByStart[g.start]; if (f === g) { f.ring.push(end); callback(f.ring); } else { fragmentByStart[f.start] = fragmentByEnd[g.end] = {start: f.start, end: g.end, ring: f.ring.concat(g.ring)}; } } else { delete fragmentByEnd[f.end]; f.ring.push(end); fragmentByEnd[f.end = endIndex] = f; } } else if (f = fragmentByStart[endIndex]) { if (g = fragmentByEnd[startIndex]) { delete fragmentByStart[f.start]; delete fragmentByEnd[g.end]; if (f === g) { f.ring.push(end); callback(f.ring); } else { fragmentByStart[g.start] = fragmentByEnd[f.end] = {start: g.start, end: f.end, ring: g.ring.concat(f.ring)}; } } else { delete fragmentByStart[f.start]; f.ring.unshift(start); fragmentByStart[f.start = startIndex] = f; } } else { fragmentByStart[startIndex] = fragmentByEnd[endIndex] = {start: startIndex, end: endIndex, ring: [start, end]}; } } } function index(point) { return point[0] * 2 + point[1] * (dx + 1) * 4; } function smoothLinear(ring, values, value) { ring.forEach(function(point) { var x = point[0], y = point[1], xt = x | 0, yt = y | 0, v0, v1 = values[yt * dx + xt]; if (x > 0 && x < dx && xt === x) { v0 = values[yt * dx + xt - 1]; point[0] = x + (value - v0) / (v1 - v0) - 0.5; } if (y > 0 && y < dy && yt === y) { v0 = values[(yt - 1) * dx + xt]; point[1] = y + (value - v0) / (v1 - v0) - 0.5; } }); } contours.size = function(_$$1) { if (!arguments.length) return [dx, dy]; var _0 = Math.ceil(_$$1[0]), _1 = Math.ceil(_$$1[1]); if (!(_0 > 0) || !(_1 > 0)) throw new Error("invalid size"); return dx = _0, dy = _1, contours; }; contours.thresholds = function(_$$1) { return arguments.length ? (threshold = typeof _$$1 === "function" ? _$$1 : Array.isArray(_$$1) ? constant$2(slice$1.call(_$$1)) : constant$2(_$$1), contours) : threshold; }; contours.smooth = function(_$$1) { return arguments.length ? (smooth = _$$1 ? smoothLinear : noop$1, contours) : smooth === smoothLinear; }; return contours; }; // TODO Optimize edge cases. // TODO Optimize index calculation. // TODO Optimize arguments. function blurX(source, target, r) { var n = source.width, m = source.height, w = (r << 1) + 1; for (var j = 0; j < m; ++j) { for (var i = 0, sr = 0; i < n + r; ++i) { if (i < n) { sr += source.data[i + j * n]; } if (i >= r) { if (i >= w) { sr -= source.data[i - w + j * n]; } target.data[i - r + j * n] = sr / Math.min(i + 1, n - 1 + w - i, w); } } } } // TODO Optimize edge cases. // TODO Optimize index calculation. // TODO Optimize arguments. function blurY(source, target, r) { var n = source.width, m = source.height, w = (r << 1) + 1; for (var i = 0; i < n; ++i) { for (var j = 0, sr = 0; j < m + r; ++j) { if (j < m) { sr += source.data[i + j * n]; } if (j >= r) { if (j >= w) { sr -= source.data[i + (j - w) * n]; } target.data[i + (j - r) * n] = sr / Math.min(j + 1, m - 1 + w - j, w); } } } } function defaultX(d) { return d[0]; } function defaultY(d) { return d[1]; } var contourDensity = function() { var x = defaultX, y = defaultY, dx = 960, dy = 500, r = 20, // blur radius k = 2, // log2(grid cell size) o = r * 3, // grid offset, to pad for blur n = (dx + o * 2) >> k, // grid width m = (dy + o * 2) >> k, // grid height threshold = constant$2(20); function density(data) { var values0 = new Float32Array(n * m), values1 = new Float32Array(n * m); data.forEach(function(d, i, data) { var xi = (x(d, i, data) + o) >> k, yi = (y(d, i, data) + o) >> k; if (xi >= 0 && xi < n && yi >= 0 && yi < m) { ++values0[xi + yi * n]; } }); // TODO Optimize. blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k); blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k); blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k); blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k); blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k); blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k); var tz = threshold(values0); // Convert number of thresholds into uniform thresholds. if (!Array.isArray(tz)) { var stop = d3Array.max(values0); tz = d3Array.tickStep(0, stop, tz); tz = d3Array.range(0, Math.floor(stop / tz) * tz, tz); tz.shift(); } return contours() .thresholds(tz) .size([n, m]) (values0) .map(transform); } function transform(geometry) { geometry.value *= Math.pow(2, -2 * k); // Density in points per square pixel. geometry.coordinates.forEach(transformPolygon); return geometry; } function transformPolygon(coordinates) { coordinates.forEach(transformRing); } function transformRing(coordinates) { coordinates.forEach(transformPoint); } // TODO Optimize. function transformPoint(coordinates) { coordinates[0] = coordinates[0] * Math.pow(2, k) - o; coordinates[1] = coordinates[1] * Math.pow(2, k) - o; } function resize() { o = r * 3; n = (dx + o * 2) >> k; m = (dy + o * 2) >> k; return density; } density.x = function(_$$1) { return arguments.length ? (x = typeof _$$1 === "function" ? _$$1 : constant$2(+_$$1), density) : x; }; density.y = function(_$$1) { return arguments.length ? (y = typeof _$$1 === "function" ? _$$1 : constant$2(+_$$1), density) : y; }; density.size = function(_$$1) { if (!arguments.length) return [dx, dy]; var _0 = Math.ceil(_$$1[0]), _1 = Math.ceil(_$$1[1]); if (!(_0 >= 0) && !(_0 >= 0)) throw new Error("invalid size"); return dx = _0, dy = _1, resize(); }; density.cellSize = function(_$$1) { if (!arguments.length) return 1 << k; if (!((_$$1 = +_$$1) >= 1)) throw new Error("invalid cell size"); return k = Math.floor(Math.log(_$$1) / Math.LN2), resize(); }; density.thresholds = function(_$$1) { return arguments.length ? (threshold = typeof _$$1 === "function" ? _$$1 : Array.isArray(_$$1) ? constant$2(slice$1.call(_$$1)) : constant$2(_$$1), density) : threshold; }; density.bandwidth = function(_$$1) { if (!arguments.length) return Math.sqrt(r * (r + 1)); if (!((_$$1 = +_$$1) >= 0)) throw new Error("invalid bandwidth"); return r = Math.round((Math.sqrt(4 * _$$1 * _$$1 + 1) - 1) / 2), resize(); }; return density; }; var CONTOUR_PARAMS = ['values', 'size']; var DENSITY_PARAMS = ['x', 'y', 'size', 'cellSize', 'bandwidth']; /** * Generate contours based on kernel-density estimation of point data. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<number>} params.size - The dimensions [width, height] over which to compute contours. * If the values parameter is provided, this must be the dimensions of the input data. * If density estimation is performed, this is the output view dimensions in pixels. * @param {Array<number>} [params.values] - An array of numeric values representing an * width x height grid of values over which to compute contours. If unspecified, this * transform will instead attempt to compute contours for the kernel density estimate * using values drawn from data tuples in the input pulse. * @param {function(object): number} [params.x] - The pixel x-coordinate accessor for density estimation. * @param {function(object): number} [params.y] - The pixel y-coordinate accessor for density estimation. * @param {number} [params.cellSize] - Contour density calculation cell size. * @param {number} [params.bandwidth] - Kernel density estimation bandwidth. * @param {Array<number>} [params.thresholds] - Contour threshold array. If * this parameter is set, the count and nice parameters will be ignored. * @param {number} [params.count] - The desired number of contours. * @param {boolean} [params.nice] - Boolean flag indicating if the contour * threshold values should be automatically aligned to "nice" * human-friendly values. Setting this flag may cause the number of * thresholds to deviate from the specified count. */ function Contour(params) { Transform.call(this, null, params); } Contour.Definition = { "type": "Contour", "metadata": {"generates": true, "source": true}, "params": [ { "name": "size", "type": "number", "array": true, "length": 2, "required": true }, { "name": "values", "type": "number", "array": true }, { "name": "x", "type": "field" }, { "name": "y", "type": "field" }, { "name": "cellSize", "type": "number" }, { "name": "bandwidth", "type": "number" }, { "name": "count", "type": "number" }, { "name": "nice", "type": "number", "default": false }, { "name": "thresholds", "type": "number", "array": true } ] }; var prototype$61 = inherits(Contour, Transform); prototype$61.transform = function(_$$1, pulse) { if (this.value && !pulse.changed() && !_$$1.modified()) return pulse.StopPropagation; var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), count = _$$1.count || 10, contour, params, values; if (_$$1.values) { contour = contours(); params = CONTOUR_PARAMS; values = _$$1.values; } else { contour = contourDensity(); params = DENSITY_PARAMS; values = pulse.materialize(pulse.SOURCE).source; } // set threshold parameter contour.thresholds(_$$1.thresholds || (_$$1.nice ? count : quantize$3(count))); // set all other parameters params.forEach(function(param) { if (_$$1[param] != null) contour[param](_$$1[param]); }); if (this.value) out.rem = this.value; this.value = out.source = out.add = contour(values).map(ingest); return out; }; function quantize$3(k) { return function(values) { var ex = d3Array.extent(values), x0 = ex[0], dx = ex[1] - x0, t = [], i = 1; for (; i<=k; ++i) t.push(x0 + dx * i / (k + 1)); return t; }; } var Feature = 'Feature'; var FeatureCollection = 'FeatureCollection'; var MultiPoint = 'MultiPoint'; /** * Consolidate an array of [longitude, latitude] points or GeoJSON features * into a combined GeoJSON object. This transform is particularly useful for * combining geo data for a Projection's fit argument. The resulting GeoJSON * data is available as this transform's value. Input pulses are unchanged. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<function(object): *>} [params.fields] - A two-element array * of field accessors for the longitude and latitude values. * @param {function(object): *} params.geojson - A field accessor for * retrieving GeoJSON feature data. */ function GeoJSON(params) { Transform.call(this, null, params); } GeoJSON.Definition = { "type": "GeoJSON", "metadata": {}, "params": [ { "name": "fields", "type": "field", "array": true, "length": 2 }, { "name": "geojson", "type": "field" }, ] }; var prototype$62 = inherits(GeoJSON, Transform); prototype$62.transform = function(_$$1, pulse) { var features = this._features, points = this._points, fields = _$$1.fields, lon = fields && fields[0], lat = fields && fields[1], geojson = _$$1.geojson, flag = pulse.ADD, mod; mod = _$$1.modified() || pulse.changed(pulse.REM) || pulse.modified(accessorFields(geojson)) || (lon && (pulse.modified(accessorFields(lon)))) || (lat && (pulse.modified(accessorFields(lat)))); if (!this.value || mod) { flag = pulse.SOURCE; this._features = (features = []); this._points = (points = []); } if (geojson) { pulse.visit(flag, function(t) { features.push(geojson(t)); }); } if (lon && lat) { pulse.visit(flag, function(t) { var x = lon(t), y = lat(t); if (x != null && y != null && (x = +x) === x && (y = +y) === y) { points.push([x, y]); } }); features = features.concat({ type: Feature, geometry: { type: MultiPoint, coordinates: points } }); } this.value = { type: FeatureCollection, features: features }; }; var defaultPath = d3Geo.geoPath(); var projectionProperties = [ // standard properties in d3-geo 'clipAngle', 'clipExtent', 'scale', 'translate', 'center', 'rotate', 'parallels', 'precision', // extended properties in d3-geo-projections 'coefficient', 'distance', 'fraction', 'lobes', 'parallel', 'radius', 'ratio', 'spacing', 'tilt' ]; /** * Augment projections with their type and a copy method. */ function create$1(type, constructor) { return function projection() { var p = constructor(); p.type = type; p.path = d3Geo.geoPath().projection(p); p.copy = p.copy || function() { var c = projection(); projectionProperties.forEach(function(prop) { if (p.hasOwnProperty(prop)) c[prop](p[prop]()); }); c.path.pointRadius(p.path.pointRadius()); return c; }; return p; }; } function projection(type, proj) { if (arguments.length > 1) { projections[type] = create$1(type, proj); return this; } else { return projections.hasOwnProperty(type) ? projections[type] : null; } } function getProjectionPath(proj) { return (proj && proj.path) || defaultPath; } var projections = { // base d3-geo projection types albers: d3Geo.geoAlbers, albersusa: d3Geo.geoAlbersUsa, azimuthalequalarea: d3Geo.geoAzimuthalEqualArea, azimuthalequidistant: d3Geo.geoAzimuthalEquidistant, conicconformal: d3Geo.geoConicConformal, conicequalarea: d3Geo.geoConicEqualArea, conicequidistant: d3Geo.geoConicEquidistant, equirectangular: d3Geo.geoEquirectangular, gnomonic: d3Geo.geoGnomonic, mercator: d3Geo.geoMercator, orthographic: d3Geo.geoOrthographic, stereographic: d3Geo.geoStereographic, transversemercator: d3Geo.geoTransverseMercator }; for (var key$2 in projections) { projection(key$2, projections[key$2]); } /** * Map GeoJSON data to an SVG path string. * @constructor * @param {object} params - The parameters for this operator. * @param {function(number, number): *} params.projection - The cartographic * projection to apply. * @param {function(object): *} [params.field] - The field with GeoJSON data, * or null if the tuple itself is a GeoJSON feature. * @param {string} [params.as='path'] - The output field in which to store * the generated path data (default 'path'). */ function GeoPath(params) { Transform.call(this, null, params); } GeoPath.Definition = { "type": "GeoPath", "metadata": {"modifies": true}, "params": [ { "name": "projection", "type": "projection" }, { "name": "field", "type": "field" }, { "name": "as", "type": "string", "default": "path" } ] }; var prototype$63 = inherits(GeoPath, Transform); prototype$63.transform = function(_$$1, pulse) { var out = pulse.fork(pulse.ALL), path$$1 = this.value, field$$1 = _$$1.field || identity, as = _$$1.as || 'path', mod; function set(t) { t[as] = path$$1(field$$1(t)); } if (!path$$1 || _$$1.modified()) { // parameters updated, reset and reflow this.value = path$$1 = getProjectionPath(_$$1.projection).context(null); out.materialize().reflow().visit(out.SOURCE, set); } else { path$$1.context(null); mod = field$$1 === identity || pulse.modified(field$$1.fields); out.visit(mod ? out.ADD_MOD : out.ADD, set); } return out.modifies(as); }; /** * Geo-code a longitude/latitude point to an x/y coordinate. * @constructor * @param {object} params - The parameters for this operator. * @param {function(number, number): *} params.projection - The cartographic * projection to apply. * @param {Array<function(object): *>} params.fields - A two-element array of * field accessors for the longitude and latitude values. * @param {Array<string>} [params.as] - A two-element array of field names * under which to store the result. Defaults to ['x','y']. */ function GeoPoint(params) { Transform.call(this, null, params); } GeoPoint.Definition = { "type": "GeoPoint", "metadata": {"modifies": true}, "params": [ { "name": "projection", "type": "projection", "required": true }, { "name": "fields", "type": "field", "array": true, "required": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["x", "y"] } ] }; var prototype$64 = inherits(GeoPoint, Transform); prototype$64.transform = function(_$$1, pulse) { var proj = _$$1.projection, lon = _$$1.fields[0], lat = _$$1.fields[1], as = _$$1.as || ['x', 'y'], x = as[0], y = as[1], mod; function set(t) { var xy = proj([lon(t), lat(t)]); if (xy) { t[x] = xy[0]; t[y] = xy[1]; } else { t[x] = undefined; t[y] = undefined; } } if (_$$1.modified()) { // parameters updated, reflow pulse = pulse.materialize().reflow(true).visit(pulse.SOURCE, set); } else { mod = pulse.modified(lon.fields) || pulse.modified(lat.fields); pulse.visit(mod ? pulse.ADD_MOD : pulse.ADD, set); } return pulse.modifies(as); }; /** * Annotate items with a geopath shape generator. * @constructor * @param {object} params - The parameters for this operator. * @param {function(number, number): *} params.projection - The cartographic * projection to apply. * @param {function(object): *} [params.field] - The field with GeoJSON data, * or null if the tuple itself is a GeoJSON feature. * @param {string} [params.as='shape'] - The output field in which to store * the generated path data (default 'shape'). */ function GeoShape(params) { Transform.call(this, null, params); } GeoShape.Definition = { "type": "GeoShape", "metadata": {"modifies": true}, "params": [ { "name": "projection", "type": "projection" }, { "name": "field", "type": "field", "default": "datum" }, { "name": "as", "type": "string", "default": "shape" } ] }; var prototype$65 = inherits(GeoShape, Transform); prototype$65.transform = function(_$$1, pulse) { var out = pulse.fork(pulse.ALL), shape = this.value, datum = _$$1.field || field('datum'), as = _$$1.as || 'shape', flag = out.ADD_MOD; if (!shape || _$$1.modified()) { // parameters updated, reset and reflow this.value = shape = shapeGenerator( getProjectionPath(_$$1.projection), datum); out.materialize().reflow(); flag = out.SOURCE; } out.visit(flag, function(t) { t[as] = shape; }); return out.modifies(as); }; function shapeGenerator(path$$1, field$$1) { var shape = function(_$$1) { return path$$1(field$$1(_$$1)); }; shape.context = function(_$$1) { path$$1.context(_$$1); return shape; }; return shape; } /** * GeoJSON feature generator for creating graticules. * @constructor */ function Graticule(params) { Transform.call(this, [], params); this.generator = d3Geo.geoGraticule(); } Graticule.Definition = { "type": "Graticule", "metadata": {"source": true, "generates": true, "changes": true}, "params": [ { "name": "extent", "type": "array", "array": true, "length": 2, "content": {"type": "number", "array": true, "length": 2} }, { "name": "extentMajor", "type": "array", "array": true, "length": 2, "content": {"type": "number", "array": true, "length": 2} }, { "name": "extentMinor", "type": "array", "array": true, "length": 2, "content": {"type": "number", "array": true, "length": 2} }, { "name": "step", "type": "number", "array": true, "length": 2 }, { "name": "stepMajor", "type": "number", "array": true, "length": 2, "default": [90, 360] }, { "name": "stepMinor", "type": "number", "array": true, "length": 2, "default": [10, 10] }, { "name": "precision", "type": "number", "default": 2.5 } ] }; var prototype$66 = inherits(Graticule, Transform); prototype$66.transform = function(_$$1, pulse) { var out = pulse.fork(), src = this.value, gen = this.generator, t; if (!src.length || _$$1.modified()) { for (var prop in _$$1) { if (isFunction(gen[prop])) { gen[prop](_$$1[prop]); } } } t = gen(); if (src.length) { out.mod.push(replace(src[0], t)); } else { out.add.push(ingest(t)); } src[0] = t; out.source = src; return out; }; /** * Maintains a cartographic projection. * @constructor * @param {object} params - The parameters for this operator. */ function Projection(params) { Transform.call(this, null, params); this.modified(true); // always treat as modified } var prototype$67 = inherits(Projection, Transform); prototype$67.transform = function(_$$1, pulse) { var proj = this.value; if (!proj || _$$1.modified('type')) { this.value = (proj = create$2(_$$1.type)); projectionProperties.forEach(function(prop) { if (_$$1[prop] != null) set$1(proj, prop, _$$1[prop]); }); } else { projectionProperties.forEach(function(prop) { if (_$$1.modified(prop)) set$1(proj, prop, _$$1[prop]); }); } if (_$$1.pointRadius != null) proj.path.pointRadius(_$$1.pointRadius); if (_$$1.fit) fit(proj, _$$1); return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); }; function fit(proj, _$$1) { var data = collectGeoJSON(_$$1.fit); _$$1.extent ? proj.fitExtent(_$$1.extent, data) : _$$1.size ? proj.fitSize(_$$1.size, data) : 0; } function create$2(type) { var constructor = projection((type || 'mercator').toLowerCase()); if (!constructor) error$1('Unrecognized projection type: ' + type); return constructor(); } function set$1(proj, key$$1, value) { if (isFunction(proj[key$$1])) proj[key$$1](value); } function collectGeoJSON(features) { features = array(features); return features.length === 1 ? features[0] : { type: FeatureCollection, features: features.reduce(function(list, f) { (f && f.type === FeatureCollection) ? list.push.apply(list, f.features) : isArray(f) ? list.push.apply(list, f) : list.push(f); return list; }, []) }; } var geo = Object.freeze({ contour: Contour, geojson: GeoJSON, geopath: GeoPath, geopoint: GeoPoint, geoshape: GeoShape, graticule: Graticule, projection: Projection }); var ForceMap = { center: d3Force.forceCenter, collide: d3Force.forceCollide, nbody: d3Force.forceManyBody, link: d3Force.forceLink, x: d3Force.forceX, y: d3Force.forceY }; var Forces = 'forces'; var ForceParams = [ 'alpha', 'alphaMin', 'alphaTarget', 'velocityDecay', 'forces' ]; var ForceConfig = ['static', 'iterations']; var ForceOutput = ['x', 'y', 'vx', 'vy']; /** * Force simulation layout. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<object>} params.forces - The forces to apply. */ function Force(params) { Transform.call(this, null, params); } Force.Definition = { "type": "Force", "metadata": {"modifies": true}, "params": [ { "name": "static", "type": "boolean", "default": false }, { "name": "restart", "type": "boolean", "default": false }, { "name": "iterations", "type": "number", "default": 300 }, { "name": "alpha", "type": "number", "default": 1 }, { "name": "alphaMin", "type": "number", "default": 0.001 }, { "name": "alphaTarget", "type": "number", "default": 0 }, { "name": "velocityDecay", "type": "number", "default": 0.4 }, { "name": "forces", "type": "param", "array": true, "params": [ { "key": {"force": "center"}, "params": [ { "name": "x", "type": "number", "default": 0 }, { "name": "y", "type": "number", "default": 0 } ] }, { "key": {"force": "collide"}, "params": [ { "name": "radius", "type": "number", "expr": true }, { "name": "strength", "type": "number", "default": 0.7 }, { "name": "iterations", "type": "number", "default": 1 } ] }, { "key": {"force": "nbody"}, "params": [ { "name": "strength", "type": "number", "default": -30 }, { "name": "theta", "type": "number", "default": 0.9 }, { "name": "distanceMin", "type": "number", "default": 1 }, { "name": "distanceMax", "type": "number" } ] }, { "key": {"force": "link"}, "params": [ { "name": "links", "type": "data" }, { "name": "id", "type": "field" }, { "name": "distance", "type": "number", "default": 30, "expr": true }, { "name": "strength", "type": "number", "expr": true }, { "name": "iterations", "type": "number", "default": 1 } ] }, { "key": {"force": "x"}, "params": [ { "name": "strength", "type": "number", "default": 0.1 }, { "name": "x", "type": "field" } ] }, { "key": {"force": "y"}, "params": [ { "name": "strength", "type": "number", "default": 0.1 }, { "name": "y", "type": "field" } ] } ] }, { "name": "as", "type": "string", "array": true, "modify": false, "default": ForceOutput } ] }; var prototype$68 = inherits(Force, Transform); prototype$68.transform = function(_$$1, pulse) { var sim = this.value, change = pulse.changed(pulse.ADD_REM), params = _$$1.modified(ForceParams), iters = _$$1.iterations || 300; // configure simulation if (!sim) { this.value = sim = simulation(pulse.source, _$$1); sim.on('tick', rerun(pulse.dataflow, this)); if (!_$$1.static) { change = true; sim.tick(); // ensure we run on init } pulse.modifies('index'); } else { if (change) { pulse.modifies('index'); sim.nodes(pulse.source); } if (params || pulse.changed(pulse.MOD)) { setup(sim, _$$1, 0, pulse); } } // run simulation if (params || change || _$$1.modified(ForceConfig) || (pulse.changed() && _$$1.restart)) { sim.alpha(Math.max(sim.alpha(), _$$1.alpha || 1)) .alphaDecay(1 - Math.pow(sim.alphaMin(), 1 / iters)); if (_$$1.static) { for (sim.stop(); --iters >= 0;) sim.tick(); } else { if (sim.stopped()) sim.restart(); if (!change) return pulse.StopPropagation; // defer to sim ticks } } return this.finish(_$$1, pulse); }; prototype$68.finish = function(_$$1, pulse) { var dataflow = pulse.dataflow; // inspect dependencies, touch link source data for (var args=this._argops, j=0, m=args.length, arg; j<m; ++j) { arg = args[j]; if (arg.name !== Forces || arg.op._argval.force !== 'link') { continue; } for (var ops=arg.op._argops, i=0, n=ops.length, op; i<n; ++i) { if (ops[i].name === 'links' && (op = ops[i].op.source)) { dataflow.pulse(op, dataflow.changeset().reflow()); break; } } } // reflow all nodes return pulse.reflow(_$$1.modified()).modifies(ForceOutput); }; function rerun(df, op) { return function() { df.touch(op).run(); } } function simulation(nodes, _$$1) { var sim = d3Force.forceSimulation(nodes), stopped = false, stop = sim.stop, restart = sim.restart; sim.stopped = function() { return stopped; }; sim.restart = function() { stopped = false; return restart(); }; sim.stop = function() { stopped = true; return stop(); }; return setup(sim, _$$1, true).on('end', function() { stopped = true; }); } function setup(sim, _$$1, init, pulse) { var f = array(_$$1.forces), i, n, p, name; for (i=0, n=ForceParams.length; i<n; ++i) { p = ForceParams[i]; if (p !== Forces && _$$1.modified(p)) sim[p](_$$1[p]); } for (i=0, n=f.length; i<n; ++i) { name = Forces + i; p = init || _$$1.modified(Forces, i) ? getForce(f[i]) : pulse && modified(f[i], pulse) ? sim.force(name) : null; if (p) sim.force(name, p); } for (n=(sim.numForces || 0); i<n; ++i) { sim.force(Forces + i, null); // remove } sim.numForces = f.length; return sim; } function modified(f, pulse) { var k, v; for (k in f) { if (isFunction(v = f[k]) && pulse.modified(accessorFields(v))) return 1; } return 0; } function getForce(_$$1) { var f, p; if (!ForceMap.hasOwnProperty(_$$1.force)) { error$1('Unrecognized force: ' + _$$1.force); } f = ForceMap[_$$1.force](); for (p in _$$1) { if (isFunction(f[p])) setForceParam(f[p], _$$1[p], _$$1); } return f; } function setForceParam(f, v, _$$1) { f(isFunction(v) ? function(d) { return v(d, _$$1); } : v); } var force = Object.freeze({ force: Force }); /** * Nest tuples into a tree structure, grouped by key values. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<function(object): *>} params.keys - The key fields to nest by, in order. * @param {function(object): *} [params.key] - Unique key field for each tuple. * If not provided, the tuple id field is used. * @param {boolean} [params.generate=false] - A boolean flag indicating if * non-leaf nodes generated by this transform should be included in the * output. The default (false) includes only the input data (leaf nodes) * in the data stream. */ function Nest(params) { Transform.call(this, null, params); } Nest.Definition = { "type": "Nest", "metadata": {"treesource": true, "source": true, "generates": true, "changes": true}, "params": [ { "name": "keys", "type": "field", "array": true }, { "name": "key", "type": "field" }, { "name": "generate", "type": "boolean" } ] }; var prototype$69 = inherits(Nest, Transform); function children(n) { return n.values; } prototype$69.transform = function(_$$1, pulse) { if (!pulse.source) { error$1('Nest transform requires an upstream data source.'); } var key$$1 = _$$1.key || tupleid, gen = _$$1.generate, mod = _$$1.modified(), out = gen || mod ? pulse.fork(pulse.ALL) : pulse, root, tree$$1, map; if (!this.value || mod || pulse.changed()) { // collect nodes to remove if (gen && this.value) { out.materialize(out.REM); this.value.each(function(node) { if (node.children) out.rem.push(node); }); } // generate new tree structure root = array(_$$1.keys) .reduce(function(n, k) { n.key(k); return n; }, d3Collection.nest()) .entries(pulse.source); this.value = tree$$1 = d3Hierarchy.hierarchy({values: root}, children); // collect nodes to add if (gen) { out.materialize(out.ADD); out.source = out.source.slice(); tree$$1.each(function(node) { if (node.children) { node = ingest(node.data); out.add.push(node); out.source.push(node); } }); } // build lookup table map = tree$$1.lookup = {}; tree$$1.each(function(node) { if (tupleid(node.data) != null) { map[key$$1(node.data)] = node; } }); } out.source.root = this.value; return out; }; /** * Abstract class for tree layout. * @constructor * @param {object} params - The parameters for this operator. */ function HierarchyLayout(params) { Transform.call(this, null, params); } var prototype$71 = inherits(HierarchyLayout, Transform); prototype$71.transform = function(_$$1, pulse) { if (!pulse.source || !pulse.source.root) { error$1(this.constructor.name + ' transform requires a backing tree data source.'); } var layout = this.layout(_$$1.method), fields = this.fields, root = pulse.source.root, as = _$$1.as || fields; if (_$$1.field) root.sum(_$$1.field); if (_$$1.sort) root.sort(_$$1.sort); setParams(layout, this.params, _$$1); try { this.value = layout(root); } catch (err) { error$1(err); } root.each(function(node) { setFields(node, fields, as); }); return pulse.reflow(_$$1.modified()).modifies(as).modifies('leaf'); }; function setParams(layout, params, _$$1) { for (var p, i=0, n=params.length; i<n; ++i) { p = params[i]; if (p in _$$1) layout[p](_$$1[p]); } } function setFields(node, fields, as) { var t = node.data; for (var i=0, n=fields.length-1; i<n; ++i) { t[as[i]] = node[fields[i]]; } t[as[n]] = node.children ? node.children.length : 0; } var Output = ['x', 'y', 'r', 'depth', 'children']; /** * Packed circle tree layout. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to size nodes. */ function Pack(params) { HierarchyLayout.call(this, params); } Pack.Definition = { "type": "Pack", "metadata": {"tree": true, "modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "sort", "type": "compare" }, { "name": "padding", "type": "number", "default": 0 }, { "name": "radius", "type": "field", "default": null }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 3, "default": Output } ] }; var prototype$70 = inherits(Pack, HierarchyLayout); prototype$70.layout = d3Hierarchy.pack; prototype$70.params = ['size', 'padding']; prototype$70.fields = Output; var Output$1 = ["x0", "y0", "x1", "y1", "depth", "children"]; /** * Partition tree layout. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to size nodes. */ function Partition(params) { HierarchyLayout.call(this, params); } Partition.Definition = { "type": "Partition", "metadata": {"tree": true, "modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "sort", "type": "compare" }, { "name": "padding", "type": "number", "default": 0 }, { "name": "round", "type": "boolean", "default": false }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 4, "default": Output$1 } ] }; var prototype$72 = inherits(Partition, HierarchyLayout); prototype$72.layout = d3Hierarchy.partition; prototype$72.params = ['size', 'round', 'padding']; prototype$72.fields = Output$1; /** * Stratify a collection of tuples into a tree structure based on * id and parent id fields. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.key - Unique key field for each tuple. * @param {function(object): *} params.parentKey - Field with key for parent tuple. */ function Stratify(params) { Transform.call(this, null, params); } Stratify.Definition = { "type": "Stratify", "metadata": {"treesource": true}, "params": [ { "name": "key", "type": "field", "required": true }, { "name": "parentKey", "type": "field", "required": true } ] }; var prototype$73 = inherits(Stratify, Transform); prototype$73.transform = function(_$$1, pulse) { if (!pulse.source) { error$1('Stratify transform requires an upstream data source.'); } var mod = _$$1.modified(), tree$$1, map, run = !this.value || mod || pulse.changed(pulse.ADD_REM) || pulse.modified(_$$1.key.fields) || pulse.modified(_$$1.parentKey.fields); if (run) { tree$$1 = d3Hierarchy.stratify().id(_$$1.key).parentId(_$$1.parentKey)(pulse.source); map = tree$$1.lookup = {}; tree$$1.each(function(node) { map[_$$1.key(node.data)] = node; }); this.value = tree$$1; } pulse.source.root = this.value; return mod ? pulse.fork(pulse.ALL) : pulse; }; var Layouts = { tidy: d3Hierarchy.tree, cluster: d3Hierarchy.cluster }; var Output$2 = ["x", "y", "depth", "children"]; /** * Tree layout. Depending on the method parameter, performs either * Reingold-Tilford 'tidy' layout or dendrogram 'cluster' layout. * @constructor * @param {object} params - The parameters for this operator. */ function Tree(params) { HierarchyLayout.call(this, params); } Tree.Definition = { "type": "Tree", "metadata": {"tree": true, "modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "sort", "type": "compare" }, { "name": "method", "type": "enum", "default": "tidy", "values": ["tidy", "cluster"] }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "nodeSize", "type": "number", "array": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 4, "default": Output$2 } ] }; var prototype$74 = inherits(Tree, HierarchyLayout); /** * Tree layout generator. Supports both 'tidy' and 'cluster' layouts. */ prototype$74.layout = function(method) { var m = method || 'tidy'; if (Layouts.hasOwnProperty(m)) return Layouts[m](); else error$1('Unrecognized Tree layout method: ' + m); }; prototype$74.params = ['size', 'nodeSize', 'separation']; prototype$74.fields = Output$2; /** * Generate tuples representing links between tree nodes. * The resulting tuples will contain 'source' and 'target' fields, * which point to parent and child node tuples, respectively. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} [params.key] - Unique key field for each tuple. * If not provided, the tuple id field is used. */ function TreeLinks(params) { Transform.call(this, {}, params); } TreeLinks.Definition = { "type": "TreeLinks", "metadata": {"tree": true, "generates": true, "changes": true}, "params": [ { "name": "key", "type": "field" } ] }; var prototype$75 = inherits(TreeLinks, Transform); function parentTuple(node) { var p; return node.parent && (p=node.parent.data) && (tupleid(p) != null) && p; } prototype$75.transform = function(_$$1, pulse) { if (!pulse.source || !pulse.source.root) { error$1('TreeLinks transform requires a backing tree data source.'); } var root = pulse.source.root, nodes = root.lookup, links = this.value, key$$1 = _$$1.key || tupleid, mods = {}, out = pulse.fork(); function modify(id$$1) { var link = links[id$$1]; if (link) { mods[id$$1] = 1; out.mod.push(link); } } // process removed tuples // assumes that if a parent node is removed the child will be, too. pulse.visit(pulse.REM, function(t) { var id$$1 = key$$1(t), link = links[id$$1]; if (link) { delete links[id$$1]; out.rem.push(link); } }); // create new link instances for added nodes with valid parents pulse.visit(pulse.ADD, function(t) { var id$$1 = key$$1(t), p; if (p = parentTuple(nodes[id$$1])) { out.add.push(links[id$$1] = ingest({source: p, target: t})); mods[id$$1] = 1; } }); // process modified nodes and their children pulse.visit(pulse.MOD, function(t) { var id$$1 = key$$1(t), node = nodes[id$$1], kids = node.children; modify(id$$1); if (kids) for (var i=0, n=kids.length; i<n; ++i) { if (!mods[(id$$1=key$$1(kids[i].data))]) modify(id$$1); } }); return out; }; var Tiles = { binary: d3Hierarchy.treemapBinary, dice: d3Hierarchy.treemapDice, slice: d3Hierarchy.treemapSlice, slicedice: d3Hierarchy.treemapSliceDice, squarify: d3Hierarchy.treemapSquarify, resquarify: d3Hierarchy.treemapResquarify }; var Output$3 = ["x0", "y0", "x1", "y1", "depth", "children"]; /** * Treemap layout. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to size nodes. */ function Treemap(params) { HierarchyLayout.call(this, params); } Treemap.Definition = { "type": "Treemap", "metadata": {"tree": true, "modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "sort", "type": "compare" }, { "name": "method", "type": "enum", "default": "squarify", "values": ["squarify", "resquarify", "binary", "dice", "slice", "slicedice"] }, { "name": "padding", "type": "number", "default": 0 }, { "name": "paddingInner", "type": "number", "default": 0 }, { "name": "paddingOuter", "type": "number", "default": 0 }, { "name": "paddingTop", "type": "number", "default": 0 }, { "name": "paddingRight", "type": "number", "default": 0 }, { "name": "paddingBottom", "type": "number", "default": 0 }, { "name": "paddingLeft", "type": "number", "default": 0 }, { "name": "ratio", "type": "number", "default": 1.618033988749895 }, { "name": "round", "type": "boolean", "default": false }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 4, "default": Output$3 } ] }; var prototype$76 = inherits(Treemap, HierarchyLayout); /** * Treemap layout generator. Adds 'method' and 'ratio' parameters * to configure the underlying tile method. */ prototype$76.layout = function() { var x = d3Hierarchy.treemap(); x.ratio = function(_$$1) { var t = x.tile(); if (t.ratio) x.tile(t.ratio(_$$1)); }; x.method = function(_$$1) { if (Tiles.hasOwnProperty(_$$1)) x.tile(Tiles[_$$1]); else error$1('Unrecognized Treemap layout method: ' + _$$1); }; return x; }; prototype$76.params = [ 'method', 'ratio', 'size', 'round', 'padding', 'paddingInner', 'paddingOuter', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft' ]; prototype$76.fields = Output$3; var tree$1 = Object.freeze({ nest: Nest, pack: Pack, partition: Partition, stratify: Stratify, tree: Tree, treelinks: TreeLinks, treemap: Treemap }); function Voronoi(params) { Transform.call(this, null, params); } Voronoi.Definition = { "type": "Voronoi", "metadata": {"modifies": true}, "params": [ { "name": "x", "type": "field", "required": true }, { "name": "y", "type": "field", "required": true }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "extent", "type": "array", "array": true, "length": 2, "default": [[-1e5, -1e5], [1e5, 1e5]], "content": {"type": "number", "array": true, "length": 2} }, { "name": "as", "type": "string", "default": "path" } ] }; var prototype$77 = inherits(Voronoi, Transform); var defaultExtent = [[-1e5, -1e5], [1e5, 1e5]]; prototype$77.transform = function(_$$1, pulse) { var as = _$$1.as || 'path', data = pulse.source, diagram, polygons, i, n; // configure and construct voronoi diagram diagram = d3Voronoi.voronoi().x(_$$1.x).y(_$$1.y); if (_$$1.size) diagram.size(_$$1.size); else diagram.extent(_$$1.extent || defaultExtent); this.value = (diagram = diagram(data)); // map polygons to paths polygons = diagram.polygons(); for (i=0, n=data.length; i<n; ++i) { data[i][as] = polygons[i] ? 'M' + polygons[i].join('L') + 'Z' : null; } return pulse.reflow(_$$1.modified()).modifies(as); }; var voronoi$1 = Object.freeze({ voronoi: Voronoi }); /* Copyright (c) 2013, Jason Davies. 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. * The name Jason Davies may not be used to endorse or promote products derived from this software without specific prior written permission. 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 JASON DAVIES 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. */ // Word cloud layout by Jason Davies, https://www.jasondavies.com/wordcloud/ // Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf var cloudRadians = Math.PI / 180; var cw = 1 << 11 >> 5; var ch = 1 << 11; var cloud = function() { var size = [256, 256], text, font, fontSize, fontStyle, fontWeight, rotate, padding, spiral = archimedeanSpiral, words = [], random = Math.random, cloud = {}, canvas = cloudCanvas; cloud.layout = function() { var contextAndRatio = getContext(canvas()), board = zeroArray((size[0] >> 5) * size[1]), bounds = null, n = words.length, i = -1, tags = [], data = words.map(function(d) { return { text: text(d), font: font(d), style: fontStyle(d), weight: fontWeight(d), rotate: rotate(d), size: ~~fontSize(d), padding: padding(d), xoff: 0, yoff: 0, x1: 0, y1: 0, x0: 0, y0: 0, hasText: false, sprite: null, datum: d }; }).sort(function(a, b) { return b.size - a.size; }); while (++i < n) { var d = data[i]; d.x = (size[0] * (random() + .5)) >> 1; d.y = (size[1] * (random() + .5)) >> 1; cloudSprite(contextAndRatio, d, data, i); if (d.hasText && place(board, d, bounds)) { tags.push(d); if (bounds) cloudBounds(bounds, d); else bounds = [{x: d.x + d.x0, y: d.y + d.y0}, {x: d.x + d.x1, y: d.y + d.y1}]; // Temporary hack d.x -= size[0] >> 1; d.y -= size[1] >> 1; } } return tags; }; function getContext(canvas) { canvas.width = canvas.height = 1; var ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2); canvas.width = (cw << 5) / ratio; canvas.height = ch / ratio; var context = canvas.getContext("2d"); context.fillStyle = context.strokeStyle = "red"; context.textAlign = "center"; return {context: context, ratio: ratio}; } function place(board, tag, bounds) { var startX = tag.x, startY = tag.y, maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]), s = spiral(size), dt = random() < .5 ? 1 : -1, t = -dt, dxdy, dx, dy; while (dxdy = s(t += dt)) { dx = ~~dxdy[0]; dy = ~~dxdy[1]; if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break; tag.x = startX + dx; tag.y = startY + dy; if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue; // TODO only check for collisions within current bounds. if (!bounds || !cloudCollide(tag, board, size[0])) { if (!bounds || collideRects(tag, bounds)) { var sprite = tag.sprite, w = tag.width >> 5, sw = size[0] >> 5, lx = tag.x - (w << 4), sx = lx & 0x7f, msx = 32 - sx, h = tag.y1 - tag.y0, x = (tag.y + tag.y0) * sw + (lx >> 5), last; for (var j = 0; j < h; j++) { last = 0; for (var i = 0; i <= w; i++) { board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0); } x += sw; } tag.sprite = null; return true; } } } return false; } cloud.words = function(_$$1) { if (arguments.length) { words = _$$1; return cloud; } else { return words; } }; cloud.size = function(_$$1) { if (arguments.length) { size = [+_$$1[0], +_$$1[1]]; return cloud; } else { return size; } }; cloud.font = function(_$$1) { if (arguments.length) { font = functor(_$$1); return cloud; } else { return font; } }; cloud.fontStyle = function(_$$1) { if (arguments.length) { fontStyle = functor(_$$1); return cloud; } else { return fontStyle; } }; cloud.fontWeight = function(_$$1) { if (arguments.length) { fontWeight = functor(_$$1); return cloud; } else { return fontWeight; } }; cloud.rotate = function(_$$1) { if (arguments.length) { rotate = functor(_$$1); return cloud; } else { return rotate; } }; cloud.text = function(_$$1) { if (arguments.length) { text = functor(_$$1); return cloud; } else { return text; } }; cloud.spiral = function(_$$1) { if (arguments.length) { spiral = spirals[_$$1] || _$$1; return cloud; } else { return spiral; } }; cloud.fontSize = function(_$$1) { if (arguments.length) { fontSize = functor(_$$1); return cloud; } else { return fontSize; } }; cloud.padding = function(_$$1) { if (arguments.length) { padding = functor(_$$1); return cloud; } else { return padding; } }; cloud.random = function(_$$1) { if (arguments.length) { random = _$$1; return cloud; } else { return random; } }; return cloud; }; // Fetches a monochrome sprite bitmap for the specified text. // Load in batches for speed. function cloudSprite(contextAndRatio, d, data, di) { if (d.sprite) return; var c = contextAndRatio.context, ratio = contextAndRatio.ratio; c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio); var x = 0, y = 0, maxh = 0, n = data.length, w, w32, h, i, j; --di; while (++di < n) { d = data[di]; c.save(); c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font; w = c.measureText(d.text + "m").width * ratio; h = d.size << 1; if (d.rotate) { var sr = Math.sin(d.rotate * cloudRadians), cr = Math.cos(d.rotate * cloudRadians), wcr = w * cr, wsr = w * sr, hcr = h * cr, hsr = h * sr; w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5; h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr)); } else { w = (w + 0x1f) >> 5 << 5; } if (h > maxh) maxh = h; if (x + w >= (cw << 5)) { x = 0; y += maxh; maxh = 0; } if (y + h >= ch) break; c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio); if (d.rotate) c.rotate(d.rotate * cloudRadians); c.fillText(d.text, 0, 0); if (d.padding) { c.lineWidth = 2 * d.padding; c.strokeText(d.text, 0, 0); } c.restore(); d.width = w; d.height = h; d.xoff = x; d.yoff = y; d.x1 = w >> 1; d.y1 = h >> 1; d.x0 = -d.x1; d.y0 = -d.y1; d.hasText = true; x += w; } var pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data, sprite = []; while (--di >= 0) { d = data[di]; if (!d.hasText) continue; w = d.width; w32 = w >> 5; h = d.y1 - d.y0; // Zero the buffer for (i = 0; i < h * w32; i++) sprite[i] = 0; x = d.xoff; if (x == null) return; y = d.yoff; var seen = 0, seenRow = -1; for (j = 0; j < h; j++) { for (i = 0; i < w; i++) { var k = w32 * j + (i >> 5), m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0; sprite[k] |= m; seen |= m; } if (seen) seenRow = j; else { d.y0++; h--; j--; y++; } } d.y1 = d.y0 + seenRow; d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32); } } // Use mask-based collision detection. function cloudCollide(tag, board, sw) { sw >>= 5; var sprite = tag.sprite, w = tag.width >> 5, lx = tag.x - (w << 4), sx = lx & 0x7f, msx = 32 - sx, h = tag.y1 - tag.y0, x = (tag.y + tag.y0) * sw + (lx >> 5), last; for (var j = 0; j < h; j++) { last = 0; for (var i = 0; i <= w; i++) { if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true; } x += sw; } return false; } function cloudBounds(bounds, d) { var b0 = bounds[0], b1 = bounds[1]; if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0; if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0; if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1; if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1; } function collideRects(a, b) { return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y; } function archimedeanSpiral(size) { var e = size[0] / size[1]; return function(t) { return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)]; }; } function rectangularSpiral(size) { var dy = 4, dx = dy * size[0] / size[1], x = 0, y = 0; return function(t) { var sign = t < 0 ? -1 : 1; // See triangular numbers: T_n = n * (n + 1) / 2. switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) { case 0: x += dx; break; case 1: y += dy; break; case 2: x -= dx; break; default: y -= dy; break; } return [x, y]; }; } // TODO reuse arrays? function zeroArray(n) { var a = [], i = -1; while (++i < n) a[i] = 0; return a; } function cloudCanvas() { try { var canvas = typeof document !== 'undefined' && document.createElement ? document.createElement('canvas') : 0; if (canvas && canvas.getContext) { return canvas; } try { return new (require('canvas'))(); } catch (e) { return new (require('canvas-prebuilt'))() } } catch (e) { error$1('Canvas unavailable. Run in browser or install node-canvas.'); } } function functor(d) { return typeof d === "function" ? d : function() { return d; }; } var spirals = { archimedean: archimedeanSpiral, rectangular: rectangularSpiral }; var Output$4 = ['x', 'y', 'font', 'fontSize', 'fontStyle', 'fontWeight', 'angle']; var Params$1 = ['text', 'font', 'rotate', 'fontSize', 'fontStyle', 'fontWeight']; function Wordcloud(params) { Transform.call(this, cloud(), params); } Wordcloud.Definition = { "type": "Wordcloud", "metadata": {"modifies": true}, "params": [ { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "font", "type": "string", "expr": true, "default": "sans-serif" }, { "name": "fontStyle", "type": "string", "expr": true, "default": "normal" }, { "name": "fontWeight", "type": "string", "expr": true, "default": "normal" }, { "name": "fontSize", "type": "number", "expr": true, "default": 14 }, { "name": "fontSizeRange", "type": "number", "array": "nullable", "default": [10, 50] }, { "name": "rotate", "type": "number", "expr": true, "default": 0 }, { "name": "text", "type": "field" }, { "name": "spiral", "type": "string", "values": ["archimedean", "rectangular"] }, { "name": "padding", "type": "number", "expr": true }, { "name": "as", "type": "string", "array": true, "length": 7, "default": Output$4 } ] }; var prototype$78 = inherits(Wordcloud, Transform); prototype$78.transform = function(_$$1, pulse) { function modp(param) { var p = _$$1[param]; return isFunction(p) && pulse.modified(p.fields); } var mod = _$$1.modified(); if (!(mod || pulse.changed(pulse.ADD_REM) || Params$1.some(modp))) return; var data = pulse.materialize(pulse.SOURCE).source, layout = this.value, as = _$$1.as || Output$4, fontSize = _$$1.fontSize || 14, range$$1; isFunction(fontSize) ? (range$$1 = _$$1.fontSizeRange) : (fontSize = constant(fontSize)); // create font size scaling function as needed if (range$$1) { var fsize = fontSize, sizeScale = scale$1('sqrt')() .domain(extent$1(fsize, data)) .range(range$$1); fontSize = function(x) { return sizeScale(fsize(x)); }; } data.forEach(function(t) { t[as[0]] = NaN; t[as[1]] = NaN; t[as[3]] = 0; }); // configure layout var words = layout .words(data) .text(_$$1.text) .size(_$$1.size || [500, 500]) .padding(_$$1.padding || 1) .spiral(_$$1.spiral || 'archimedean') .rotate(_$$1.rotate || 0) .font(_$$1.font || 'sans-serif') .fontStyle(_$$1.fontStyle || 'normal') .fontWeight(_$$1.fontWeight || 'normal') .fontSize(fontSize) .random(exports.random) .layout(); var size = layout.size(), dx = size[0] >> 1, dy = size[1] >> 1, i = 0, n = words.length, w, t; for (; i<n; ++i) { w = words[i]; t = w.datum; t[as[0]] = w.x + dx; t[as[1]] = w.y + dy; t[as[2]] = w.font; t[as[3]] = w.size; t[as[4]] = w.style; t[as[5]] = w.weight; t[as[6]] = w.rotate; } return pulse.reflow(mod).modifies(as); }; function extent$1(field$$1, data) { var min$$1 = +Infinity, max$$1 = -Infinity, i = 0, n = data.length, v; for (; i<n; ++i) { v = field$$1(data[i]); if (v < min$$1) min$$1 = v; if (v > max$$1) max$$1 = v; } return [min$$1, max$$1]; } var wordcloud = Object.freeze({ wordcloud: Wordcloud }); function array8(n) { return new Uint8Array(n); } function array16(n) { return new Uint16Array(n); } function array32(n) { return new Uint32Array(n); } /** * Maintains CrossFilter state. */ function Bitmaps() { var width = 8, data = [], seen = array32(0), curr = array$2(0, width), prev = array$2(0, width); return { data: function() { return data; }, seen: function() { return (seen = lengthen(seen, data.length)); }, add: function(array) { for (var i=0, j=data.length, n=array.length, t; i<n; ++i) { t = array[i]; t._index = j++; data.push(t); } }, remove: function(num, map) { // map: index -> boolean (true => remove) var n = data.length, copy = Array(n - num), reindex = data, // reuse old data array for index map t, i, j; // seek forward to first removal for (i=0; !map[i] && i<n; ++i) { copy[i] = data[i]; reindex[i] = i; } // condense arrays for (j=i; i<n; ++i) { t = data[i]; if (!map[i]) { reindex[i] = j; curr[j] = curr[i]; prev[j] = prev[i]; copy[j] = t; t._index = j++; } else { reindex[i] = -1; } curr[i] = 0; // clear unused bits } data = copy; return reindex; }, size: function() { return data.length; }, curr: function() { return curr; }, prev: function() { return prev; }, reset: function(k) { prev[k] = curr[k]; }, all: function() { return width < 0x101 ? 0xff : width < 0x10001 ? 0xffff : 0xffffffff; }, set: function(k, one) { curr[k] |= one; }, clear: function(k, one) { curr[k] &= ~one; }, resize: function(n, m) { var k = curr.length; if (n > k || m > width) { width = Math.max(m, width); curr = array$2(n, width, curr); prev = array$2(n, width); } } }; } function lengthen(array, length, copy) { if (array.length >= length) return array; copy = copy || new array.constructor(length); copy.set(array); return copy; } function array$2(n, m, array) { var copy = (m < 0x101 ? array8 : m < 0x10001 ? array16 : array32)(n); if (array) copy.set(array); return copy; } var Dimension = function(index, i, query) { var bit = (1 << i); return { one: bit, zero: ~bit, range: query.slice(), bisect: index.bisect, index: index.index, size: index.size, onAdd: function(added, curr) { var dim = this, range$$1 = dim.bisect(dim.range, added.value), idx = added.index, lo = range$$1[0], hi = range$$1[1], n1 = idx.length, i; for (i=0; i<lo; ++i) curr[idx[i]] |= bit; for (i=hi; i<n1; ++i) curr[idx[i]] |= bit; return dim; } }; }; /** * Maintains a list of values, sorted by key. */ function SortedIndex() { var index = array32(0), value = [], size = 0; function insert(key, data, base) { if (!data.length) return []; var n0 = size, n1 = data.length, addv = Array(n1), addi = array32(n1), oldv, oldi, i; for (i=0; i<n1; ++i) { addv[i] = key(data[i]); addi[i] = i; } addv = sort(addv, addi); if (n0) { oldv = value; oldi = index; value = Array(n0 + n1); index = array32(n0 + n1); merge$2(base, oldv, oldi, n0, addv, addi, n1, value, index); } else { if (base > 0) for (i=0; i<n1; ++i) { addi[i] += base; } value = addv; index = addi; } size = n0 + n1; return {index: addi, value: addv}; } function remove(num, map) { // map: index -> remove var n = size, idx, i, j; // seek forward to first removal for (i=0; !map[index[i]] && i<n; ++i); // condense index and value arrays for (j=i; i<n; ++i) { if (!map[idx=index[i]]) { index[j] = idx; value[j] = value[i]; ++j; } } size = n - num; } function reindex(map) { for (var i=0, n=size; i<n; ++i) { index[i] = map[index[i]]; } } function bisect$$1(range$$1, array) { var n; if (array) { n = array.length; } else { array = value; n = size; } return [ d3Array.bisectLeft(array, range$$1[0], 0, n), d3Array.bisectRight(array, range$$1[1], 0, n) ]; } return { insert: insert, remove: remove, bisect: bisect$$1, reindex: reindex, index: function() { return index; }, size: function() { return size; } }; } function sort(values, index) { values.sort.call(index, function(a, b) { var x = values[a], y = values[b]; return x < y ? -1 : x > y ? 1 : 0; }); return d3Array.permute(values, index); } function merge$2(base, value0, index0, n0, value1, index1, n1, value, index) { var i0 = 0, i1 = 0, i; for (i=0; i0 < n0 && i1 < n1; ++i) { if (value0[i0] < value1[i1]) { value[i] = value0[i0]; index[i] = index0[i0++]; } else { value[i] = value1[i1]; index[i] = index1[i1++] + base; } } for (; i0 < n0; ++i0, ++i) { value[i] = value0[i0]; index[i] = index0[i0]; } for (; i1 < n1; ++i1, ++i) { value[i] = value1[i1]; index[i] = index1[i1] + base; } } /** * An indexed multi-dimensional filter. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<function(object): *>} params.fields - An array of dimension accessors to filter. * @param {Array} params.query - An array of per-dimension range queries. */ function CrossFilter(params) { Transform.call(this, Bitmaps(), params); this._indices = null; this._dims = null; } CrossFilter.Definition = { "type": "CrossFilter", "metadata": {}, "params": [ { "name": "fields", "type": "field", "array": true, "required": true }, { "name": "query", "type": "array", "array": true, "required": true, "content": {"type": "number", "array": true, "length": 2} } ] }; var prototype$79 = inherits(CrossFilter, Transform); prototype$79.transform = function(_$$1, pulse) { if (!this._dims) { return this.init(_$$1, pulse); } else { var init = _$$1.modified('fields') || _$$1.fields.some(function(f) { return pulse.modified(f.fields); }); return init ? this.reinit(_$$1, pulse) : this.eval(_$$1, pulse); } }; prototype$79.init = function(_$$1, pulse) { var fields = _$$1.fields, query = _$$1.query, indices = this._indices = {}, dims = this._dims = [], m = query.length, i = 0, key$$1, index; // instantiate indices and dimensions for (; i<m; ++i) { key$$1 = fields[i].fname; index = indices[key$$1] || (indices[key$$1] = SortedIndex()); dims.push(Dimension(index, i, query[i])); } return this.eval(_$$1, pulse); }; prototype$79.reinit = function(_$$1, pulse) { var output = pulse.materialize().fork(), fields = _$$1.fields, query = _$$1.query, indices = this._indices, dims = this._dims, bits = this.value, curr = bits.curr(), prev = bits.prev(), all = bits.all(), out = (output.rem = output.add), mod = output.mod, m = query.length, adds = {}, add, index, key$$1, mods, remMap, modMap, i, n, f; // set prev to current state prev.set(curr); // if pulse has remove tuples, process them first if (pulse.rem.length) { remMap = this.remove(_$$1, pulse, output); } // if pulse has added tuples, add them to state if (pulse.add.length) { bits.add(pulse.add); } // if pulse has modified tuples, create an index map if (pulse.mod.length) { modMap = {}; for (mods=pulse.mod, i=0, n=mods.length; i<n; ++i) { modMap[mods[i]._index] = 1; } } // re-initialize indices as needed, update curr bitmap for (i=0; i<m; ++i) { f = fields[i]; if (!dims[i] || _$$1.modified('fields', i) || pulse.modified(f.fields)) { key$$1 = f.fname; if (!(add = adds[key$$1])) { indices[key$$1] = index = SortedIndex(); adds[key$$1] = add = index.insert(f, pulse.source, 0); } dims[i] = Dimension(index, i, query[i]).onAdd(add, curr); } } // visit each tuple // if filter state changed, push index to add/rem // else if in mod and passes a filter, push index to mod for (i=0, n=bits.data().length; i<n; ++i) { if (remMap[i]) { // skip if removed tuple continue; } else if (prev[i] !== curr[i]) { // add if state changed out.push(i); } else if (modMap[i] && curr[i] !== all) { // otherwise, pass mods through mod.push(i); } } bits.mask = (1 << m) - 1; return output; }; prototype$79.eval = function(_$$1, pulse) { var output = pulse.materialize().fork(), m = this._dims.length, mask = 0; if (pulse.rem.length) { this.remove(_$$1, pulse, output); mask |= (1 << m) - 1; } if (_$$1.modified('query') && !_$$1.modified('fields')) { mask |= this.update(_$$1, pulse, output); } if (pulse.add.length) { this.insert(_$$1, pulse, output); mask |= (1 << m) - 1; } if (pulse.mod.length) { this.modify(pulse, output); mask |= (1 << m) - 1; } this.value.mask = mask; return output; }; prototype$79.insert = function(_$$1, pulse, output) { var tuples = pulse.add, bits = this.value, dims = this._dims, indices = this._indices, fields = _$$1.fields, adds = {}, out = output.add, k = bits.size(), n = k + tuples.length, m = dims.length, j, key$$1, add; // resize bitmaps and add tuples as needed bits.resize(n, m); bits.add(tuples); var curr = bits.curr(), prev = bits.prev(), all = bits.all(); // add to dimensional indices for (j=0; j<m; ++j) { key$$1 = fields[j].fname; add = adds[key$$1] || (adds[key$$1] = indices[key$$1].insert(fields[j], tuples, k)); dims[j].onAdd(add, curr); } // set previous filters, output if passes at least one filter for (; k<n; ++k) { prev[k] = all; if (curr[k] !== all) out.push(k); } }; prototype$79.modify = function(pulse, output) { var out = output.mod, bits = this.value, curr = bits.curr(), all = bits.all(), tuples = pulse.mod, i, n, k; for (i=0, n=tuples.length; i<n; ++i) { k = tuples[i]._index; if (curr[k] !== all) out.push(k); } }; prototype$79.remove = function(_$$1, pulse, output) { var indices = this._indices, bits = this.value, curr = bits.curr(), prev = bits.prev(), all = bits.all(), map = {}, out = output.rem, tuples = pulse.rem, i, n, k, f; // process tuples, output if passes at least one filter for (i=0, n=tuples.length; i<n; ++i) { k = tuples[i]._index; map[k] = 1; // build index map prev[k] = (f = curr[k]); curr[k] = all; if (f !== all) out.push(k); } // remove from dimensional indices for (k in indices) { indices[k].remove(n, map); } this.reindex(pulse, n, map); return map; }; // reindex filters and indices after propagation completes prototype$79.reindex = function(pulse, num, map) { var indices = this._indices, bits = this.value; pulse.runAfter(function() { var indexMap = bits.remove(num, map); for (var key$$1 in indices) indices[key$$1].reindex(indexMap); }); }; prototype$79.update = function(_$$1, pulse, output) { var dims = this._dims, query = _$$1.query, stamp = pulse.stamp, m = dims.length, mask = 0, i, q; // survey how many queries have changed output.filters = 0; for (q=0; q<m; ++q) { if (_$$1.modified('query', q)) { i = q; ++mask; } } if (mask === 1) { // only one query changed, use more efficient update mask = dims[i].one; this.incrementOne(dims[i], query[i], output.add, output.rem); } else { // multiple queries changed, perform full record keeping for (q=0, mask=0; q<m; ++q) { if (!_$$1.modified('query', q)) continue; mask |= dims[q].one; this.incrementAll(dims[q], query[q], stamp, output.add); output.rem = output.add; // duplicate add/rem for downstream resolve } } return mask; }; prototype$79.incrementAll = function(dim, query, stamp, out) { var bits = this.value, seen = bits.seen(), curr = bits.curr(), prev = bits.prev(), index = dim.index(), old = dim.bisect(dim.range), range$$1 = dim.bisect(query), lo1 = range$$1[0], hi1 = range$$1[1], lo0 = old[0], hi0 = old[1], one$$1 = dim.one, i, j, k; // Fast incremental update based on previous lo index. if (lo1 < lo0) { for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) { k = index[i]; if (seen[k] !== stamp) { prev[k] = curr[k]; seen[k] = stamp; out.push(k); } curr[k] ^= one$$1; } } else if (lo1 > lo0) { for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) { k = index[i]; if (seen[k] !== stamp) { prev[k] = curr[k]; seen[k] = stamp; out.push(k); } curr[k] ^= one$$1; } } // Fast incremental update based on previous hi index. if (hi1 > hi0) { for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) { k = index[i]; if (seen[k] !== stamp) { prev[k] = curr[k]; seen[k] = stamp; out.push(k); } curr[k] ^= one$$1; } } else if (hi1 < hi0) { for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) { k = index[i]; if (seen[k] !== stamp) { prev[k] = curr[k]; seen[k] = stamp; out.push(k); } curr[k] ^= one$$1; } } dim.range = query.slice(); }; prototype$79.incrementOne = function(dim, query, add, rem) { var bits = this.value, curr = bits.curr(), index = dim.index(), old = dim.bisect(dim.range), range$$1 = dim.bisect(query), lo1 = range$$1[0], hi1 = range$$1[1], lo0 = old[0], hi0 = old[1], one$$1 = dim.one, i, j, k; // Fast incremental update based on previous lo index. if (lo1 < lo0) { for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) { k = index[i]; curr[k] ^= one$$1; add.push(k); } } else if (lo1 > lo0) { for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) { k = index[i]; curr[k] ^= one$$1; rem.push(k); } } // Fast incremental update based on previous hi index. if (hi1 > hi0) { for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) { k = index[i]; curr[k] ^= one$$1; add.push(k); } } else if (hi1 < hi0) { for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) { k = index[i]; curr[k] ^= one$$1; rem.push(k); } } dim.range = query.slice(); }; /** * Selectively filters tuples by resolving against a filter bitmap. * Useful for processing the output of a cross-filter transform. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.ignore - A bit mask indicating which filters to ignore. * @param {object} params.filter - The per-tuple filter bitmaps. Typically this * parameter value is a reference to a {@link CrossFilter} transform. */ function ResolveFilter(params) { Transform.call(this, null, params); } ResolveFilter.Definition = { "type": "ResolveFilter", "metadata": {}, "params": [ { "name": "ignore", "type": "number", "required": true, "description": "A bit mask indicating which filters to ignore." }, { "name": "filter", "type": "object", "required": true, "description": "Per-tuple filter bitmaps from a CrossFilter transform." } ] }; var prototype$80 = inherits(ResolveFilter, Transform); prototype$80.transform = function(_$$1, pulse) { var ignore = ~(_$$1.ignore || 0), // bit mask where zeros -> dims to ignore bitmap = _$$1.filter, mask = bitmap.mask; // exit early if no relevant filter changes if ((mask & ignore) === 0) return pulse.StopPropagation; var output = pulse.fork(pulse.ALL), data = bitmap.data(), curr = bitmap.curr(), prev = bitmap.prev(), pass = function(k) { return !(curr[k] & ignore) ? data[k] : null; }; // propagate all mod tuples that pass the filter output.filter(output.MOD, pass); // determine add & rem tuples via filter functions // for efficiency, we do *not* populate new arrays, // instead we add filter functions applied downstream if (!(mask & (mask-1))) { // only one filter changed output.filter(output.ADD, pass); output.filter(output.REM, function(k) { return (curr[k] & ignore) === mask ? data[k] : null; }); } else { // multiple filters changed output.filter(output.ADD, function(k) { var c = curr[k] & ignore, f = !c && (c ^ (prev[k] & ignore)); return f ? data[k] : null; }); output.filter(output.REM, function(k) { var c = curr[k] & ignore, f = c && !(c ^ (c ^ (prev[k] & ignore))); return f ? data[k] : null; }); } // add filter to source data in case of reflow... return output.filter(output.SOURCE, function(t) { return pass(t._index); }); }; var xf = Object.freeze({ crossfilter: CrossFilter, resolvefilter: ResolveFilter }); var version = "3.0.9"; var Default = 'default'; var cursor = function(view) { var cursor = view._signals.cursor; // add cursor signal to dataflow, if needed if (!cursor) { view._signals.cursor = (cursor = view.add({user: Default, item: null})); } // evaluate cursor on each mousemove event view.on(view.events('view', 'mousemove'), cursor, function(_$$1, event) { var value = cursor.value, user = value ? (isString(value) ? value : value.user) : Default, item = event.item && event.item.cursor || null; return (value && user === value.user && item == value.item) ? value : {user: user, item: item}; } ); // when cursor signal updates, set visible cursor view.add(null, function(_$$1) { var user = _$$1.cursor, item = this.value; if (!isString(user)) { item = user.item; user = user.user; } setCursor(user && user !== Default ? user : (item || user)); return item; }, {cursor: cursor}); }; function setCursor(cursor) { // set cursor on document body // this ensures cursor applies even if dragging out of view if (typeof document !== 'undefined' && document.body) { document.body.style.cursor = cursor; } } function dataref(view, name) { var data = view._runtime.data; if (!data.hasOwnProperty(name)) { error$1('Unrecognized data set: ' + name); } return data[name]; } function data(name) { return dataref(this, name).values.value; } function change(name, changes) { if (!isChangeSet(changes)) { error$1('Second argument to changes must be a changeset.'); } var dataset = dataref(this, name); dataset.modified = true; return this.pulse(dataset.input, changes); } function insert(name, _$$1) { return change.call(this, name, changeset().insert(_$$1)); } function remove(name, _$$1) { return change.call(this, name, changeset().remove(_$$1)); } function width(view) { var padding = view.padding(); return Math.max(0, view._viewWidth + padding.left + padding.right); } function height$1(view) { var padding = view.padding(); return Math.max(0, view._viewHeight + padding.top + padding.bottom); } function offset$1(view) { var padding = view.padding(), origin = view._origin; return [ padding.left + origin[0], padding.top + origin[1] ]; } function resizeRenderer(view) { var origin = offset$1(view); view._renderer.background(view._background); view._renderer.resize(width(view), height$1(view), origin); view._handler.origin(origin); } /** * Extend an event with additional view-specific methods. * Adds a new property ('vega') to an event that provides a number * of methods for querying information about the current interaction. * The vega object provides the following methods: * view - Returns the backing View instance. * item - Returns the currently active scenegraph item (if any). * group - Returns the currently active scenegraph group (if any). * This method accepts a single string-typed argument indicating the name * of the desired parent group. The scenegraph will be traversed from * the item up towards the root to search for a matching group. If no * argument is provided the enclosing group for the active item is * returned, unless the item it itself a group, in which case it is * returned directly. * xy - Returns a two-element array containing the x and y coordinates for * mouse or touch events. For touch events, this is based on the first * elements in the changedTouches array. This method accepts a single * argument: either an item instance or mark name that should serve as * the reference coordinate system. If no argument is provided the * top-level view coordinate system is assumed. * x - Returns the current x-coordinate, accepts the same arguments as xy. * y - Returns the current y-coordinate, accepts the same arguments as xy. * @param {Event} event - The input event to extend. * @param {Item} item - The currently active scenegraph item (if any). * @return {Event} - The extended input event. */ var eventExtend = function(view, event, item) { var el = view._renderer.scene(), p, e, translate; if (el) { translate = offset$1(view); e = event.changedTouches ? event.changedTouches[0] : event; p = point(e, el); p[0] -= translate[0]; p[1] -= translate[1]; } event.dataflow = view; event.vega = extension(view, item, p); event.item = item; return event; }; function extension(view, item, point$$1) { var itemGroup = item ? item.mark.marktype === 'group' ? item : item.mark.group : null; function group(name) { var g = itemGroup, i; if (name) for (i = item; i; i = i.mark.group) { if (i.mark.name === name) { g = i; break; } } return g && g.mark && g.mark.interactive ? g : {}; } function xy(item) { if (!item) return point$$1; if (isString(item)) item = group(item); var p = point$$1.slice(); while (item) { p[0] -= item.x || 0; p[1] -= item.y || 0; item = item.mark && item.mark.group; } return p; } return { view: constant(view), item: constant(item || {}), group: group, xy: xy, x: function(item) { return xy(item)[0]; }, y: function(item) { return xy(item)[1]; } }; } var VIEW = 'view'; var WINDOW = 'window'; /** * Initialize event handling configuration. * @param {object} config - The configuration settings. * @return {object} */ function initializeEventConfig(config) { config = extend({}, config); var def = config.defaults; if (def) { if (isArray(def.prevent)) { def.prevent = toSet(def.prevent); } if (isArray(def.allow)) { def.allow = toSet(def.allow); } } return config; } function prevent(view, type) { var def = view._eventConfig.defaults, prevent = def && def.prevent, allow = def && def.allow; return prevent === false || allow === true ? false : prevent === true || allow === false ? true : prevent ? prevent[type] : allow ? !allow[type] : view.preventDefault(); } /** * Create a new event stream from an event source. * @param {object} source - The event source to monitor. * @param {string} type - The event type. * @param {function(object): boolean} [filter] - Event filter function. * @return {EventStream} */ function events$1(source, type, filter) { var view = this, s = new EventStream(filter), send = function(e, item) { if (source === VIEW && prevent(view, type)) { e.preventDefault(); } try { s.receive(eventExtend(view, e, item)); } catch (error) { view.error(error); } finally { view.run(); } }, sources; if (source === VIEW) { view.addEventListener(type, send); return s; } if (source === WINDOW) { if (typeof window !== 'undefined') sources = [window]; } else if (typeof document !== 'undefined') { sources = document.querySelectorAll(source); } if (!sources) { view.warn('Can not resolve event source: ' + source); return s; } for (var i=0, n=sources.length; i<n; ++i) { sources[i].addEventListener(type, send); } view._eventListeners.push({ type: type, sources: sources, handler: send }); return s; } function itemFilter(event) { return event.item; } function markTarget(event) { // grab upstream collector feeding the mark operator var source = event.item.mark.source; return source.source || source; } function invoke(name) { return function(_$$1, event) { return event.vega.view() .changeset() .encode(event.item, name); }; } var hover = function(hoverSet, leaveSet) { hoverSet = [hoverSet || 'hover']; leaveSet = [leaveSet || 'update', hoverSet]; // invoke hover set upon mouseover this.on( this.events('view', 'mouseover', itemFilter), markTarget, invoke(hoverSet) ); // invoke leave set upon mouseout this.on( this.events('view', 'mouseout', itemFilter), markTarget, invoke(leaveSet) ); return this; }; /** * Remove all external event listeners. */ var finalize = function() { var listeners = this._eventListeners, n = listeners.length, m, e; while (--n >= 0) { e = listeners[n]; m = e.sources.length; while (--m >= 0) { e.sources[m].removeEventListener(e.type, e.handler); } } }; var element$1 = function(tag, attr, text) { var el = document.createElement(tag); for (var key in attr) el.setAttribute(key, attr[key]); if (text != null) el.textContent = text; return el; }; var BindClass = 'vega-bind'; var NameClass = 'vega-bind-name'; var RadioClass = 'vega-bind-radio'; var OptionClass = 'vega-option-'; /** * Bind a signal to an external HTML input element. The resulting two-way * binding will propagate input changes to signals, and propagate signal * changes to the input element state. If this view instance has no parent * element, we assume the view is headless and no bindings are created. * @param {Element|string} el - The parent DOM element to which the input * element should be appended as a child. If string-valued, this argument * will be treated as a CSS selector. If null or undefined, the parent * element of this view will be used as the element. * @param {object} param - The binding parameters which specify the signal * to bind to, the input element type, and type-specific configuration. * @return {View} - This view instance. */ var bind$1 = function(view, el, binding) { if (!el) return; var param = binding.param, bind = binding.state; if (!bind) { bind = binding.state = { elements: null, active: false, set: null, update: function(value) { bind.source = true; view.signal(param.signal, value).run(); } }; if (param.debounce) { bind.update = debounce(param.debounce, bind.update); } } generate(bind, el, param, view.signal(param.signal)); if (!bind.active) { view.on(view._signals[param.signal], null, function() { bind.source ? (bind.source = false) : bind.set(view.signal(param.signal)); }); bind.active = true; } return bind; }; /** * Generate an HTML input form element and bind it to a signal. */ function generate(bind, el, param, value) { var div = element$1('div', {'class': BindClass}); div.appendChild(element$1('span', {'class': NameClass}, (param.name || param.signal) )); el.appendChild(div); var input = form; switch (param.input) { case 'checkbox': input = checkbox; break; case 'select': input = select; break; case 'radio': input = radio; break; case 'range': input = range$1; break; } input(bind, div, param, value); } /** * Generates an arbitrary input form element. * The input type is controlled via user-provided parameters. */ function form(bind, el, param, value) { var node = element$1('input'); for (var key$$1 in param) { if (key$$1 !== 'signal' && key$$1 !== 'element') { node.setAttribute(key$$1 === 'input' ? 'type' : key$$1, param[key$$1]); } } node.setAttribute('name', param.signal); node.value = value; el.appendChild(node); node.addEventListener('input', function() { bind.update(node.value); }); bind.elements = [node]; bind.set = function(value) { node.value = value; }; } /** * Generates a checkbox input element. */ function checkbox(bind, el, param, value) { var attr = {type: 'checkbox', name: param.signal}; if (value) attr.checked = true; var node = element$1('input', attr); el.appendChild(node); node.addEventListener('change', function() { bind.update(node.checked); }); bind.elements = [node]; bind.set = function(value) { node.checked = !!value || null; }; } /** * Generates a selection list input element. */ function select(bind, el, param, value) { var node = element$1('select', {name: param.signal}); param.options.forEach(function(option) { var attr = {value: option}; if (valuesEqual(option, value)) attr.selected = true; node.appendChild(element$1('option', attr, option+'')); }); el.appendChild(node); node.addEventListener('change', function() { bind.update(param.options[node.selectedIndex]); }); bind.elements = [node]; bind.set = function(value) { for (var i=0, n=param.options.length; i<n; ++i) { if (valuesEqual(param.options[i], value)) { node.selectedIndex = i; return; } } }; } /** * Generates a radio button group. */ function radio(bind, el, param, value) { var group = element$1('span', {'class': RadioClass}); el.appendChild(group); bind.elements = param.options.map(function(option) { var id$$1 = OptionClass + param.signal + '-' + option; var attr = { id: id$$1, type: 'radio', name: param.signal, value: option }; if (valuesEqual(option, value)) attr.checked = true; var input = element$1('input', attr); input.addEventListener('change', function() { bind.update(option); }); group.appendChild(input); group.appendChild(element$1('label', {'for': id$$1}, option+'')); return input; }); bind.set = function(value) { var nodes = bind.elements, i = 0, n = nodes.length; for (; i<n; ++i) { if (valuesEqual(nodes[i].value, value)) nodes[i].checked = true; } }; } /** * Generates a slider input element. */ function range$1(bind, el, param, value) { value = value !== undefined ? value : ((+param.max) + (+param.min)) / 2; var min$$1 = param.min || Math.min(0, +value) || 0, max$$1 = param.max || Math.max(100, +value) || 100, step = param.step || d3Array.tickStep(min$$1, max$$1, 100); var node = element$1('input', { type: 'range', name: param.signal, min: min$$1, max: max$$1, step: step }); node.value = value; var label = element$1('label', {}, +value); el.appendChild(node); el.appendChild(label); function update() { label.textContent = node.value; bind.update(+node.value); } // subscribe to both input and change // signal updates halt redundant values, maintaining performance node.addEventListener('input', update); node.addEventListener('change', update); bind.elements = [node]; bind.set = function(value) { node.value = value; label.textContent = value; }; } function valuesEqual(a, b) { return a === b || (a+'' === b+''); } var initializeRenderer = function(view, r, el, constructor, scaleFactor) { r = r || new constructor(view.loader()); return r .initialize(el, width(view), height$1(view), offset$1(view), scaleFactor) .background(view._background); }; var initializeHandler = function(view, prevHandler, el, constructor) { var handler = new constructor() .scene(view.scenegraph().root) .initialize(el, offset$1(view), view); if (prevHandler) { handler.handleTooltip = prevHandler.handleTooltip; prevHandler.handlers().forEach(function(h) { handler.on(h.type, h.handler); }); } return handler; }; var initialize$1 = function(el, elBind) { var view = this, type = view._renderType, module = renderModule(type), Handler$$1, Renderer$$1; // containing dom element el = view._el = el ? lookup$2(view, el) : null; // select appropriate renderer & handler if (!module) view.error('Unrecognized renderer type: ' + type); Handler$$1 = module.handler || CanvasHandler; Renderer$$1 = (el ? module.renderer : module.headless); // initialize renderer and input handler view._renderer = !Renderer$$1 ? null : initializeRenderer(view, view._renderer, el, Renderer$$1); view._handler = initializeHandler(view, view._handler, el, Handler$$1); view._redraw = true; // initialize signal bindings if (el) { elBind = elBind ? lookup$2(view, elBind) : el.appendChild(element$1('div', {'class': 'vega-bindings'})); view._bind.forEach(function(_$$1) { if (_$$1.param.element) { _$$1.element = lookup$2(view, _$$1.param.element); } }); view._bind.forEach(function(_$$1) { bind$1(view, _$$1.element || elBind, _$$1); }); } return view; }; function lookup$2(view, el) { if (typeof el === 'string') { if (typeof document !== 'undefined') { el = document.querySelector(el); if (!el) { view.error('Signal bind element not found: ' + el); return null; } } else { view.error('DOM document instance not found.'); return null; } } if (el) { try { el.innerHTML = ''; } catch (e) { el = null; view.error(e); } } return el; } /** * Render the current scene in a headless fashion. * This method is asynchronous, returning a Promise instance. * @return {Promise} - A Promise that resolves to a renderer. */ var renderHeadless = function(view, type, scaleFactor) { var module = renderModule(type), ctr = module && module.headless; return !ctr ? Promise.reject('Unrecognized renderer type: ' + type) : view.runAsync().then(function() { return initializeRenderer(view, null, null, ctr, scaleFactor) .renderAsync(view._scenegraph.root); }); }; /** * Produce an image URL for the visualization. Depending on the type * parameter, the generated URL contains data for either a PNG or SVG image. * The URL can be used (for example) to download images of the visualization. * This method is asynchronous, returning a Promise instance. * @param {string} type - The image type. One of 'svg', 'png' or 'canvas'. * The 'canvas' and 'png' types are synonyms for a PNG image. * @return {Promise} - A promise that resolves to an image URL. */ var renderToImageURL = function(type, scaleFactor) { return (type !== RenderType.Canvas && type !== RenderType.SVG && type !== RenderType.PNG) ? Promise.reject('Unrecognized image type: ' + type) : renderHeadless(this, type, scaleFactor).then(function(renderer) { return type === RenderType.SVG ? toBlobURL(renderer.svg(), 'image/svg+xml') : renderer.canvas().toDataURL('image/png'); }); }; function toBlobURL(data, mime) { var blob = new Blob([data], {type: mime}); return window.URL.createObjectURL(blob); } /** * Produce a Canvas instance containing a rendered visualization. * This method is asynchronous, returning a Promise instance. * @return {Promise} - A promise that resolves to a Canvas instance. */ var renderToCanvas = function(scaleFactor) { return renderHeadless(this, RenderType.Canvas, scaleFactor) .then(function(renderer) { return renderer.canvas(); }); }; /** * Produce a rendered SVG string of the visualization. * This method is asynchronous, returning a Promise instance. * @return {Promise} - A promise that resolves to an SVG string. */ var renderToSVG = function(scaleFactor) { return renderHeadless(this, RenderType.SVG, scaleFactor) .then(function(renderer) { return renderer.svg(); }); }; var parseAutosize = function(spec, config) { spec = spec || config.autosize; if (isObject(spec)) { return spec; } else { spec = spec || 'pad'; return {type: spec}; } }; var parsePadding = function(spec, config) { spec = spec || config.padding; return isObject(spec) ? { top: number$1(spec.top), bottom: number$1(spec.bottom), left: number$1(spec.left), right: number$1(spec.right) } : paddingObject(number$1(spec)); }; function number$1(_$$1) { return +_$$1 || 0; } function paddingObject(_$$1) { return {top: _$$1, bottom: _$$1, left: _$$1, right: _$$1}; } var OUTER = 'outer'; var OUTER_INVALID = ['value', 'update', 'react', 'bind']; function outerError(prefix, name) { error$1(prefix + ' for "outer" push: ' + $$2(name)); } var parseSignal = function(signal, scope) { var name = signal.name; if (signal.push === OUTER) { // signal must already be defined, raise error if not if (!scope.signals[name]) outerError('No prior signal definition', name); // signal push must not use properties reserved for standard definition OUTER_INVALID.forEach(function(prop) { if (signal[prop] !== undefined) outerError('Invalid property ', prop); }); } else { // define a new signal in the current scope var op = scope.addSignal(name, signal.value); if (signal.react === false) op.react = false; if (signal.bind) scope.addBinding(name, signal.bind); } }; function ASTNode(type) { this.type = type; } ASTNode.prototype.visit = function(visitor) { var node = this, c, i, n; if (visitor(node)) return 1; for (c=children$1(node), i=0, n=c.length; i<n; ++i) { if (c[i].visit(visitor)) return 1; } }; function children$1(node) { switch (node.type) { case 'ArrayExpression': return node.elements; case 'BinaryExpression': case 'LogicalExpression': return [node.left, node.right]; case 'CallExpression': var args = node.arguments.slice(); args.unshift(node.callee); return args; case 'ConditionalExpression': return [node.test, node.consequent, node.alternate]; case 'MemberExpression': return [node.object, node.property]; case 'ObjectExpression': return node.properties; case 'Property': return [node.key, node.value]; case 'UnaryExpression': return [node.argument]; case 'Identifier': case 'Literal': case 'RawCode': default: return []; } } /* The following expression parser is based on Esprima (http://esprima.org/). Original header comment and license for Esprima is included here: Copyright (C) 2013 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2013 Thaddee Tyl <thaddee.tyl@gmail.com> Copyright (C) 2013 Mathias Bynens <mathias@qiwi.be> Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com> Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be> Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl> Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com> Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com> Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com> Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var source$1; var index; var length; var lookahead; var TokenBooleanLiteral = 1; var TokenEOF = 2; var TokenIdentifier = 3; var TokenKeyword = 4; var TokenNullLiteral = 5; var TokenNumericLiteral = 6; var TokenPunctuator = 7; var TokenStringLiteral = 8; var SyntaxArrayExpression = 'ArrayExpression'; var SyntaxBinaryExpression = 'BinaryExpression'; var SyntaxCallExpression = 'CallExpression'; var SyntaxConditionalExpression = 'ConditionalExpression'; var SyntaxIdentifier = 'Identifier'; var SyntaxLiteral = 'Literal'; var SyntaxLogicalExpression = 'LogicalExpression'; var SyntaxMemberExpression = 'MemberExpression'; var SyntaxObjectExpression = 'ObjectExpression'; var SyntaxProperty = 'Property'; var SyntaxUnaryExpression = 'UnaryExpression'; // Error messages should be identical to V8. var MessageUnexpectedToken = 'Unexpected token %0'; var MessageUnexpectedNumber = 'Unexpected number'; var MessageUnexpectedString = 'Unexpected string'; var MessageUnexpectedIdentifier = 'Unexpected identifier'; var MessageUnexpectedReserved = 'Unexpected reserved word'; var MessageUnexpectedEOS = 'Unexpected end of input'; var MessageInvalidRegExp = 'Invalid regular expression'; var MessageUnterminatedRegExp = 'Invalid regular expression: missing /'; var MessageStrictOctalLiteral = 'Octal literals are not allowed in strict mode.'; var MessageStrictDuplicateProperty = 'Duplicate data property in object literal not allowed in strict mode'; var ILLEGAL = 'ILLEGAL'; var DISABLED = 'Disabled.'; // See also tools/generate-unicode-regex.py. var RegexNonAsciiIdentifierStart = new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'); var RegexNonAsciiIdentifierPart = new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'); // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { /* istanbul ignore next */ if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 0x30 && ch <= 0x39); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) (ch >= 0x41 && ch <= 0x5A) || // A..Z (ch >= 0x61 && ch <= 0x7A) || // a..z (ch === 0x5C) || // \ (backslash) ((ch >= 0x80) && RegexNonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) (ch >= 0x41 && ch <= 0x5A) || // A..Z (ch >= 0x61 && ch <= 0x7A) || // a..z (ch >= 0x30 && ch <= 0x39) || // 0..9 (ch === 0x5C) || // \ (backslash) ((ch >= 0x80) && RegexNonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.1 Keywords var keywords$1 = { 'if':1, 'in':1, 'do':1, 'var':1, 'for':1, 'new':1, 'try':1, 'let':1, 'this':1, 'else':1, 'case':1, 'void':1, 'with':1, 'enum':1, 'while':1, 'break':1, 'catch':1, 'throw':1, 'const':1, 'yield':1, 'class':1, 'super':1, 'return':1, 'typeof':1, 'delete':1, 'switch':1, 'export':1, 'import':1, 'public':1, 'static':1, 'default':1, 'finally':1, 'extends':1, 'package':1, 'private':1, 'function':1, 'continue':1, 'debugger':1, 'interface':1, 'protected':1, 'instanceof':1, 'implements':1 }; function skipComment() { var ch; while (index < length) { ch = source$1.charCodeAt(index); if (isWhiteSpace(ch) || isLineTerminator(ch)) { ++index; } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source$1[index])) { ch = source$1[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { throwError({}, MessageUnexpectedToken, ILLEGAL); } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source$1[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, MessageUnexpectedToken, ILLEGAL); } while (index < length) { ch = source$1[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, MessageUnexpectedToken, ILLEGAL); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source$1.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (U+005C, U+0075) denotes an escaped character. if (ch === 0x5C) { if (source$1.charCodeAt(index) !== 0x75) { throwError({}, MessageUnexpectedToken, ILLEGAL); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } id = ch; } while (index < length) { ch = source$1.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (U+005C, U+0075) denotes an escaped character. if (ch === 0x5C) { id = id.substr(0, id.length - 1); if (source$1.charCodeAt(index) !== 0x75) { throwError({}, MessageUnexpectedToken, ILLEGAL); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source$1.charCodeAt(index); if (ch === 0x5C) { // Blackslash (U+005C) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source$1.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (U+005C) starts an escaped character. id = (source$1.charCodeAt(index) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = TokenIdentifier; } else if (keywords$1.hasOwnProperty(id)) { type = TokenKeyword; } else if (id === 'null') { type = TokenNullLiteral; } else if (id === 'true' || id === 'false') { type = TokenBooleanLiteral; } else { type = TokenIdentifier; } return { type: type, value: id, start: start, end: index }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source$1.charCodeAt(index), code2, ch1 = source$1[index], ch2, ch3, ch4; switch (code) { // Check for most common single-character punctuators. case 0x2E: // . dot case 0x28: // ( open bracket case 0x29: // ) close bracket case 0x3B: // ; semicolon case 0x2C: // , comma case 0x7B: // { open curly brace case 0x7D: // } close curly brace case 0x5B: // [ case 0x5D: // ] case 0x3A: // : case 0x3F: // ? case 0x7E: // ~ ++index; return { type: TokenPunctuator, value: String.fromCharCode(code), start: start, end: index }; default: code2 = source$1.charCodeAt(index + 1); // '=' (U+003D) marks an assignment or comparison operator. if (code2 === 0x3D) { switch (code) { case 0x2B: // + case 0x2D: // - case 0x2F: // / case 0x3C: // < case 0x3E: // > case 0x5E: // ^ case 0x7C: // | case 0x25: // % case 0x26: // & case 0x2A: // * index += 2; return { type: TokenPunctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), start: start, end: index }; case 0x21: // ! case 0x3D: // = index += 2; // !== and === if (source$1.charCodeAt(index) === 0x3D) { ++index; } return { type: TokenPunctuator, value: source$1.slice(start, index), start: start, end: index }; } } } // 4-character punctuator: >>>= ch4 = source$1.substr(index, 4); if (ch4 === '>>>=') { index += 4; return { type: TokenPunctuator, value: ch4, start: start, end: index }; } // 3-character punctuators: === !== >>> <<= >>= ch3 = ch4.substr(0, 3); if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') { index += 3; return { type: TokenPunctuator, value: ch3, start: start, end: index }; } // Other 2-character punctuators: ++ -- << >> && || ch2 = ch3.substr(0, 2); if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') { index += 2; return { type: TokenPunctuator, value: ch2, start: start, end: index }; } // 1-character punctuators: < > = ! + - * % & | ^ / if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: TokenPunctuator, value: ch1, start: start, end: index }; } throwError({}, MessageUnexpectedToken, ILLEGAL); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source$1[index])) { break; } number += source$1[index++]; } if (number.length === 0) { throwError({}, MessageUnexpectedToken, ILLEGAL); } if (isIdentifierStart(source$1.charCodeAt(index))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } return { type: TokenNumericLiteral, value: parseInt('0x' + number, 16), start: start, end: index }; } function scanOctalLiteral(start) { var number = '0' + source$1[index++]; while (index < length) { if (!isOctalDigit(source$1[index])) { break; } number += source$1[index++]; } if (isIdentifierStart(source$1.charCodeAt(index)) || isDecimalDigit(source$1.charCodeAt(index))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } return { type: TokenNumericLiteral, value: parseInt(number, 8), octal: true, start: start, end: index }; } function scanNumericLiteral() { var number, start, ch; ch = source$1[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source$1[index++]; ch = source$1[index]; // Hex number starts with '0x'. // Octal number starts with '0'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (isOctalDigit(ch)) { return scanOctalLiteral(start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } } while (isDecimalDigit(source$1.charCodeAt(index))) { number += source$1[index++]; } ch = source$1[index]; } if (ch === '.') { number += source$1[index++]; while (isDecimalDigit(source$1.charCodeAt(index))) { number += source$1[index++]; } ch = source$1[index]; } if (ch === 'e' || ch === 'E') { number += source$1[index++]; ch = source$1[index]; if (ch === '+' || ch === '-') { number += source$1[index++]; } if (isDecimalDigit(source$1.charCodeAt(index))) { while (isDecimalDigit(source$1.charCodeAt(index))) { number += source$1[index++]; } } else { throwError({}, MessageUnexpectedToken, ILLEGAL); } } if (isIdentifierStart(source$1.charCodeAt(index))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } return { type: TokenNumericLiteral, value: parseFloat(number), start: start, end: index }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, octal = false; quote = source$1[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source$1[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source$1[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'u': case 'x': if (source$1[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { str += scanHexEscape(ch); } break; case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source$1[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source$1[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source$1[index])) { code = code * 8 + '01234567'.indexOf(source$1[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { if (ch === '\r' && source$1[index] === '\n') { ++index; } } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, MessageUnexpectedToken, ILLEGAL); } return { type: TokenStringLiteral, value: str, octal: octal, start: start, end: index }; } function testRegExp(pattern, flags) { var tmp = pattern; if (flags.indexOf('u') >= 0) { // Replace each astral symbol and every Unicode code point // escape sequence with a single ASCII symbol to avoid throwing on // regular expressions that are only valid in combination with the // `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it // would be replaced by `[x-b]` which throws an error. tmp = tmp .replace(/\\u\{([0-9a-fA-F]+)\}/g, function($0, $1) { if (parseInt($1, 16) <= 0x10FFFF) { return 'x'; } throwError({}, MessageInvalidRegExp); }) .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); } // First, detect invalid regular expressions. try { new RegExp(tmp); } catch (e) { throwError({}, MessageInvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { return null; } } function scanRegExpBody() { var ch, str, classMarker, terminated, body; ch = source$1[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source$1[index++]; classMarker = false; terminated = false; while (index < length) { ch = source$1[index++]; str += ch; if (ch === '\\') { ch = source$1[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, MessageUnterminatedRegExp); } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, MessageUnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { throwError({}, MessageUnterminatedRegExp); } // Exclude leading and trailing slash. body = str.substr(1, str.length - 2); return { value: body, literal: str }; } function scanRegExpFlags() { var ch, str, flags; str = ''; flags = ''; while (index < length) { ch = source$1[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { throwError({}, MessageUnexpectedToken, ILLEGAL); } else { flags += ch; str += ch; } } if (flags.search(/[^gimuy]/g) >= 0) { throwError({}, MessageInvalidRegExp, flags); } return { value: flags, literal: str }; } function scanRegExp() { var start, body, flags, value; lookahead = null; skipComment(); start = index; body = scanRegExpBody(); flags = scanRegExpFlags(); value = testRegExp(body.value, flags.value); return { literal: body.literal + flags.literal, value: value, regex: { pattern: body.value, flags: flags.value }, start: start, end: index }; } function isIdentifierName(token) { return token.type === TokenIdentifier || token.type === TokenKeyword || token.type === TokenBooleanLiteral || token.type === TokenNullLiteral; } function advance() { var ch; skipComment(); if (index >= length) { return { type: TokenEOF, start: index, end: index }; } ch = source$1.charCodeAt(index); if (isIdentifierStart(ch)) { return scanIdentifier(); } // Very common: ( and ) and ; if (ch === 0x28 || ch === 0x29 || ch === 0x3B) { return scanPunctuator(); } // String literal starts with single quote (U+0027) or double quote (U+0022). if (ch === 0x27 || ch === 0x22) { return scanStringLiteral(); } // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (ch === 0x2E) { if (isDecimalDigit(source$1.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.end; lookahead = advance(); index = token.end; return token; } function peek$1() { var pos; pos = index; lookahead = advance(); index = pos; } function finishArrayExpression(elements) { var node = new ASTNode(SyntaxArrayExpression); node.elements = elements; return node; } function finishBinaryExpression(operator, left, right) { var node = new ASTNode((operator === '||' || operator === '&&') ? SyntaxLogicalExpression : SyntaxBinaryExpression); node.operator = operator; node.left = left; node.right = right; return node; } function finishCallExpression(callee, args) { var node = new ASTNode(SyntaxCallExpression); node.callee = callee; node.arguments = args; return node; } function finishConditionalExpression(test, consequent, alternate) { var node = new ASTNode(SyntaxConditionalExpression); node.test = test; node.consequent = consequent; node.alternate = alternate; return node; } function finishIdentifier(name) { var node = new ASTNode(SyntaxIdentifier); node.name = name; return node; } function finishLiteral(token) { var node = new ASTNode(SyntaxLiteral); node.value = token.value; node.raw = source$1.slice(token.start, token.end); if (token.regex) { if (node.raw === '//') { node.raw = '/(?:)/'; } node.regex = token.regex; } return node; } function finishMemberExpression(accessor, object, property) { var node = new ASTNode(SyntaxMemberExpression); node.computed = accessor === '['; node.object = object; node.property = property; if (!node.computed) property.member = true; return node; } function finishObjectExpression(properties) { var node = new ASTNode(SyntaxObjectExpression); node.properties = properties; return node; } function finishProperty(kind, key, value) { var node = new ASTNode(SyntaxProperty); node.key = key; node.value = value; node.kind = kind; return node; } function finishUnaryExpression(operator, argument) { var node = new ASTNode(SyntaxUnaryExpression); node.operator = operator; node.argument = argument; node.prefix = true; return node; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function(whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); error = new Error(msg); error.index = index; error.description = msg; throw error; } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === TokenEOF) { throwError(token, MessageUnexpectedEOS); } if (token.type === TokenNumericLiteral) { throwError(token, MessageUnexpectedNumber); } if (token.type === TokenStringLiteral) { throwError(token, MessageUnexpectedString); } if (token.type === TokenIdentifier) { throwError(token, MessageUnexpectedIdentifier); } if (token.type === TokenKeyword) { throwError(token, MessageUnexpectedReserved); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, MessageUnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== TokenPunctuator || token.value !== value) { throwUnexpected(token); } } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === TokenPunctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { return lookahead.type === TokenKeyword && lookahead.value === keyword; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = []; index = lookahead.start; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { elements.push(parseConditionalExpression()); if (!match(']')) { expect(','); } } } lex(); return finishArrayExpression(elements); } // 11.1.5 Object Initialiser function parseObjectPropertyKey() { var token; index = lookahead.start; token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === TokenStringLiteral || token.type === TokenNumericLiteral) { if (token.octal) { throwError(token, MessageStrictOctalLiteral); } return finishLiteral(token); } return finishIdentifier(token.value); } function parseObjectProperty() { var token, key, id, value; index = lookahead.start; token = lookahead; if (token.type === TokenIdentifier) { id = parseObjectPropertyKey(); expect(':'); value = parseConditionalExpression(); return finishProperty('init', id, value); } if (token.type === TokenEOF || token.type === TokenPunctuator) { throwUnexpected(token); } else { key = parseObjectPropertyKey(); expect(':'); value = parseConditionalExpression(); return finishProperty('init', key, value); } } function parseObjectInitialiser() { var properties = [], property, name, key, map = {}, toString = String; index = lookahead.start; expect('{'); while (!match('}')) { property = parseObjectProperty(); if (property.key.type === SyntaxIdentifier) { name = property.key.name; } else { name = toString(property.key.value); } key = '$' + name; if (Object.prototype.hasOwnProperty.call(map, key)) { throwError({}, MessageStrictDuplicateProperty); } else { map[key] = true; } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return finishObjectExpression(properties); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); expr = parseExpression$1(); expect(')'); return expr; } // 11.1 Primary Expressions var legalKeywords = { "if": 1, "this": 1 }; function parsePrimaryExpression() { var type, token, expr; if (match('(')) { return parseGroupExpression(); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } type = lookahead.type; index = lookahead.start; if (type === TokenIdentifier || legalKeywords[lookahead.value]) { expr = finishIdentifier(lex().value); } else if (type === TokenStringLiteral || type === TokenNumericLiteral) { if (lookahead.octal) { throwError(lookahead, MessageStrictOctalLiteral); } expr = finishLiteral(lex()); } else if (type === TokenKeyword) { throw new Error(DISABLED); } else if (type === TokenBooleanLiteral) { token = lex(); token.value = (token.value === 'true'); expr = finishLiteral(token); } else if (type === TokenNullLiteral) { token = lex(); token.value = null; expr = finishLiteral(token); } else if (match('/') || match('/=')) { expr = finishLiteral(scanRegExp()); peek$1(); } else { throwUnexpected(lex()); } return expr; } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = []; expect('('); if (!match(')')) { while (index < length) { args.push(parseConditionalExpression()); if (match(')')) { break; } expect(','); } } expect(')'); return args; } function parseNonComputedProperty() { var token; index = lookahead.start; token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return finishIdentifier(token.value); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression$1(); expect(']'); return expr; } function parseLeftHandSideExpressionAllowCall() { var expr, args, property; expr = parsePrimaryExpression(); for (;;) { if (match('.')) { property = parseNonComputedMember(); expr = finishMemberExpression('.', expr, property); } else if (match('(')) { args = parseArguments(); expr = finishCallExpression(expr, args); } else if (match('[')) { property = parseComputedMember(); expr = finishMemberExpression('[', expr, property); } else { break; } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var expr = parseLeftHandSideExpressionAllowCall(); if (lookahead.type === TokenPunctuator) { if ((match('++') || match('--'))) { throw new Error(DISABLED); } } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var token, expr; if (lookahead.type !== TokenPunctuator && lookahead.type !== TokenKeyword) { expr = parsePostfixExpression(); } else if (match('++') || match('--')) { throw new Error(DISABLED); } else if (match('+') || match('-') || match('~') || match('!')) { token = lex(); expr = parseUnaryExpression(); expr = finishUnaryExpression(token.value, expr); } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { throw new Error(DISABLED); } else { expr = parsePostfixExpression(); } return expr; } function binaryPrecedence(token) { var prec = 0; if (token.type !== TokenPunctuator && token.type !== TokenKeyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': case 'in': prec = 7; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var marker, markers, expr, token, prec, stack, right, operator, left, i; marker = lookahead; left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, lookahead]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); markers.pop(); expr = finishBinaryExpression(operator, left, right); stack.push(expr); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(lookahead); expr = parseUnaryExpression(); stack.push(expr); } // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { markers.pop(); expr = finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, consequent, alternate; expr = parseBinaryExpression(); if (match('?')) { lex(); consequent = parseConditionalExpression(); expect(':'); alternate = parseConditionalExpression(); expr = finishConditionalExpression(expr, consequent, alternate); } return expr; } // 11.14 Comma Operator function parseExpression$1() { var expr = parseConditionalExpression(); if (match(',')) { throw new Error(DISABLED); // no sequence expressions } return expr; } var parse$3 = function(code) { source$1 = code; index = 0; length = source$1.length; lookahead = null; peek$1(); var expr = parseExpression$1(); if (lookahead.type !== TokenEOF) { throw new Error("Unexpect token after expression."); } return expr; }; var Constants = { NaN: 'NaN', E: 'Math.E', LN2: 'Math.LN2', LN10: 'Math.LN10', LOG2E: 'Math.LOG2E', LOG10E: 'Math.LOG10E', PI: 'Math.PI', SQRT1_2: 'Math.SQRT1_2', SQRT2: 'Math.SQRT2', MIN_VALUE: 'Number.MIN_VALUE', MAX_VALUE: 'Number.MAX_VALUE' }; var Functions = function(codegen) { function fncall(name, args, cast, type) { var obj = codegen(args[0]); if (cast) { obj = cast + '(' + obj + ')'; if (cast.lastIndexOf('new ', 0) === 0) obj = '(' + obj + ')'; } return obj + '.' + name + (type < 0 ? '' : type === 0 ? '()' : '(' + args.slice(1).map(codegen).join(',') + ')'); } function fn(name, cast, type) { return function(args) { return fncall(name, args, cast, type); }; } var DATE = 'new Date', STRING = 'String', REGEXP = 'RegExp'; return { // MATH functions isNaN: 'isNaN', isFinite: 'isFinite', abs: 'Math.abs', acos: 'Math.acos', asin: 'Math.asin', atan: 'Math.atan', atan2: 'Math.atan2', ceil: 'Math.ceil', cos: 'Math.cos', exp: 'Math.exp', floor: 'Math.floor', log: 'Math.log', max: 'Math.max', min: 'Math.min', pow: 'Math.pow', random: 'Math.random', round: 'Math.round', sin: 'Math.sin', sqrt: 'Math.sqrt', tan: 'Math.tan', clamp: function(args) { if (args.length < 3) error$1('Missing arguments to clamp function.'); if (args.length > 3) error$1('Too many arguments to clamp function.'); var a = args.map(codegen); return 'Math.max('+a[1]+', Math.min('+a[2]+','+a[0]+'))'; }, // DATE functions now: 'Date.now', utc: 'Date.UTC', datetime: DATE, date: fn('getDate', DATE, 0), day: fn('getDay', DATE, 0), year: fn('getFullYear', DATE, 0), month: fn('getMonth', DATE, 0), hours: fn('getHours', DATE, 0), minutes: fn('getMinutes', DATE, 0), seconds: fn('getSeconds', DATE, 0), milliseconds: fn('getMilliseconds', DATE, 0), time: fn('getTime', DATE, 0), timezoneoffset: fn('getTimezoneOffset', DATE, 0), utcdate: fn('getUTCDate', DATE, 0), utcday: fn('getUTCDay', DATE, 0), utcyear: fn('getUTCFullYear', DATE, 0), utcmonth: fn('getUTCMonth', DATE, 0), utchours: fn('getUTCHours', DATE, 0), utcminutes: fn('getUTCMinutes', DATE, 0), utcseconds: fn('getUTCSeconds', DATE, 0), utcmilliseconds: fn('getUTCMilliseconds', DATE, 0), // shared sequence functions length: fn('length', null, -1), indexof: fn('indexOf', null), lastindexof: fn('lastIndexOf', null), slice: fn('slice', null), // STRING functions parseFloat: 'parseFloat', parseInt: 'parseInt', upper: fn('toUpperCase', STRING, 0), lower: fn('toLowerCase', STRING, 0), substring: fn('substring', STRING), replace: fn('replace', STRING), // REGEXP functions regexp: REGEXP, test: fn('test', REGEXP), // Control Flow functions if: function(args) { if (args.length < 3) error$1('Missing arguments to if function.'); if (args.length > 3) error$1('Too many arguments to if function.'); var a = args.map(codegen); return '('+a[0]+'?'+a[1]+':'+a[2]+')'; } }; }; var codegen = function(opt) { opt = opt || {}; var whitelist = opt.whitelist ? toSet(opt.whitelist) : {}, blacklist = opt.blacklist ? toSet(opt.blacklist) : {}, constants = opt.constants || Constants, functions = (opt.functions || Functions)(visit), globalvar = opt.globalvar, fieldvar = opt.fieldvar, globals = {}, fields = {}, memberDepth = 0; var outputGlobal = isFunction(globalvar) ? globalvar : function (id$$1) { return globalvar + '["' + id$$1 + '"]'; }; function visit(ast) { if (isString(ast)) return ast; var generator = Generators[ast.type]; if (generator == null) error$1('Unsupported type: ' + ast.type); return generator(ast); } var Generators = { Literal: function(n) { return n.raw; }, Identifier: function(n) { var id$$1 = n.name; if (memberDepth > 0) { return id$$1; } else if (blacklist.hasOwnProperty(id$$1)) { return error$1('Illegal identifier: ' + id$$1); } else if (constants.hasOwnProperty(id$$1)) { return constants[id$$1]; } else if (whitelist.hasOwnProperty(id$$1)) { return id$$1; } else { globals[id$$1] = 1; return outputGlobal(id$$1); } }, MemberExpression: function(n) { var d = !n.computed; var o = visit(n.object); if (d) memberDepth += 1; var p = visit(n.property); if (o === fieldvar) { fields[p] = 1; } // HACKish... if (d) memberDepth -= 1; return o + (d ? '.'+p : '['+p+']'); }, CallExpression: function(n) { if (n.callee.type !== 'Identifier') { error$1('Illegal callee type: ' + n.callee.type); } var callee = n.callee.name; var args = n.arguments; var fn = functions.hasOwnProperty(callee) && functions[callee]; if (!fn) error$1('Unrecognized function: ' + callee); return isFunction(fn) ? fn(args) : fn + '(' + args.map(visit).join(',') + ')'; }, ArrayExpression: function(n) { return '[' + n.elements.map(visit).join(',') + ']'; }, BinaryExpression: function(n) { return '(' + visit(n.left) + n.operator + visit(n.right) + ')'; }, UnaryExpression: function(n) { return '(' + n.operator + visit(n.argument) + ')'; }, ConditionalExpression: function(n) { return '(' + visit(n.test) + '?' + visit(n.consequent) + ':' + visit(n.alternate) + ')'; }, LogicalExpression: function(n) { return '(' + visit(n.left) + n.operator + visit(n.right) + ')'; }, ObjectExpression: function(n) { return '{' + n.properties.map(visit).join(',') + '}'; }, Property: function(n) { memberDepth += 1; var k = visit(n.key); memberDepth -= 1; return k + ':' + visit(n.value); } }; function codegen(ast) { var result = { code: visit(ast), globals: Object.keys(globals), fields: Object.keys(fields) }; globals = {}; fields = {}; return result; } codegen.functions = functions; codegen.constants = constants; return codegen; }; var formatCache = {}; function formatter(type, method, specifier) { var k = type + ':' + specifier, e = formatCache[k]; if (!e || e[0] !== method) { formatCache[k] = (e = [method, method(specifier)]); } return e[1]; } function format$1(_$$1, specifier) { return formatter('format', d3Format.format, specifier)(_$$1); } function timeFormat$1(_$$1, specifier) { return formatter('timeFormat', d3TimeFormat.timeFormat, specifier)(_$$1); } function utcFormat$1(_$$1, specifier) { return formatter('utcFormat', d3TimeFormat.utcFormat, specifier)(_$$1); } function timeParse$1(_$$1, specifier) { return formatter('timeParse', d3TimeFormat.timeParse, specifier)(_$$1); } function utcParse$1(_$$1, specifier) { return formatter('utcParse', d3TimeFormat.utcParse, specifier)(_$$1); } var dateObj = new Date(2000, 0, 1); function time$1(month, day, specifier) { dateObj.setMonth(month); dateObj.setDate(day); return timeFormat$1(dateObj, specifier); } function monthFormat(month) { return time$1(month, 1, '%B'); } function monthAbbrevFormat(month) { return time$1(month, 1, '%b'); } function dayFormat(day) { return time$1(0, 2 + day, '%A'); } function dayAbbrevFormat(day) { return time$1(0, 2 + day, '%a'); } function quarter(date) { return 1 + ~~(new Date(date).getMonth() / 3); } function utcquarter(date) { return 1 + ~~(new Date(date).getUTCMonth() / 3); } function log$2(df, method, args) { try { df[method].apply(df, ['EXPRESSION'].concat([].slice.call(args))); } catch (err) { df.warn(err); } return args[args.length-1]; } function warn() { return log$2(this.context.dataflow, 'warn', arguments); } function info() { return log$2(this.context.dataflow, 'info', arguments); } function debug() { return log$2(this.context.dataflow, 'debug', arguments); } var inScope = function(item) { var group = this.context.group, value = false; if (group) while (item) { if (item === group) { value = true; break; } item = item.mark.group; } return value; }; /** * Span-preserving range clamp. If the span of the input range is less * than (max - min) and an endpoint exceeds either the min or max value, * the range is translated such that the span is preserved and one * endpoint touches the boundary of the min/max range. * If the span exceeds (max - min), the range [min, max] is returned. */ var clampRange = function(range$$1, min$$1, max$$1) { var lo = range$$1[0], hi = range$$1[1], span; if (hi < lo) { span = hi; hi = lo; lo = span; } span = hi - lo; return span >= (max$$1 - min$$1) ? [min$$1, max$$1] : [ Math.min(Math.max(lo, min$$1), max$$1 - span), Math.min(Math.max(hi, span), max$$1) ]; }; function pinchDistance(event) { var t = event.touches, dx = t[0].clientX - t[1].clientX, dy = t[0].clientY - t[1].clientY; return Math.sqrt(dx * dx + dy * dy); } function pinchAngle(event) { var t = event.touches; return Math.atan2( t[0].clientY - t[1].clientY, t[0].clientX - t[1].clientX ); } var _window = (typeof window !== 'undefined' && window) || null; function screen() { return _window ? _window.screen : {}; } function windowSize() { return _window ? [_window.innerWidth, _window.innerHeight] : [undefined, undefined]; } function containerSize() { var view = this.context.dataflow, el = view.container && view.container(); return el ? [el.clientWidth, el.clientHeight] : [undefined, undefined]; } var flush = function(range$$1, value, threshold, left, right, center) { var l = Math.abs(value - range$$1[0]), r = Math.abs(peek(range$$1) - value); return l < r && l <= threshold ? left : r <= threshold ? right : center; }; var span = function(array) { return (array[array.length-1] - array[0]) || 0; }; var Literal = 'Literal'; var Identifier$1 = 'Identifier'; var indexPrefix = '@'; var scalePrefix = '%'; var dataPrefix = ':'; function getScale(name, ctx) { var s; return isFunction(name) ? name : isString(name) ? (s = ctx.scales[name]) && s.value : undefined; } function addScaleDependency(scope, params, name) { var scaleName = scalePrefix + name; if (!params.hasOwnProperty(scaleName)) { try { params[scaleName] = scope.scaleRef(name); } catch (err) { // TODO: error handling? warning? } } } function scaleVisitor(name, args, scope, params) { if (args[0].type === Literal) { // add scale dependency addScaleDependency(scope, params, args[0].value); } else if (args[0].type === Identifier$1) { // indirect scale lookup; add all scales as parameters for (name in scope.scales) { addScaleDependency(scope, params, name); } } } function range$2(name, group) { var s = getScale(name, (group || this).context); return s && s.range ? s.range() : []; } function domain(name, group) { var s = getScale(name, (group || this).context); return s ? s.domain() : []; } function bandwidth(name, group) { var s = getScale(name, (group || this).context); return s && s.bandwidth ? s.bandwidth() : 0; } function bandspace(count, paddingInner, paddingOuter) { return bandSpace(count || 0, paddingInner || 0, paddingOuter || 0); } function copy(name, group) { var s = getScale(name, (group || this).context); return s ? s.copy() : undefined; } function scale$2(name, value, group) { var s = getScale(name, (group || this).context); return s ? s(value) : undefined; } function invert(name, range$$1, group) { var s = getScale(name, (group || this).context); return !s ? undefined : isArray(range$$1) ? (s.invertRange || s.invert)(range$$1) : (s.invert || s.invertExtent)(range$$1); } var scaleGradient = function(scale, p0, p1, count) { var gradient = Gradient(p0, p1), stops = scale.domain(), min$$1 = stops[0], max$$1 = stops[stops.length-1], fraction = scaleFraction(scale, min$$1, max$$1); if (scale.ticks) { stops = scale.ticks(+count || 15); if (min$$1 !== stops[0]) stops.unshift(min$$1); if (max$$1 !== stops[stops.length-1]) stops.push(max$$1); } for (var i=0, n=stops.length; i<n; ++i) { gradient.stop(fraction(stops[i]), scale(stops[i])); } return gradient; }; function geoMethod(method) { return function(projection, geojson, group) { var p = getScale(projection, (group || this).context); return p && p.path[method](geojson); }; } var geoArea = geoMethod('area'); var geoBounds = geoMethod('bounds'); var geoCentroid = geoMethod('centroid'); function data$1(name) { var data = this.context.data[name]; return data ? data.values.value : []; } function dataVisitor(name, args, scope, params) { if (args[0].type !== Literal) { error$1('First argument to data functions must be a string literal.'); } var data = args[0].value, dataName = dataPrefix + data; if (!params.hasOwnProperty(dataName)) { params[dataName] = scope.getData(data).tuplesRef(); } } function indata(name, field$$1, value) { var index = this.context.data[name]['index:' + field$$1], entry = index ? index.value.get(value) : undefined; return entry ? entry.count : entry; } function indataVisitor(name, args, scope, params) { if (args[0].type !== Literal) error$1('First argument to indata must be a string literal.'); if (args[1].type !== Literal) error$1('Second argument to indata must be a string literal.'); var data = args[0].value, field$$1 = args[1].value, indexName = indexPrefix + field$$1; if (!params.hasOwnProperty(indexName)) { params[indexName] = scope.getData(data).indataRef(scope, field$$1); } } function setdata(name, tuples) { var df = this.context.dataflow, data = this.context.data[name], input = data.input; df.pulse(input, df.changeset().remove(truthy).insert(tuples)); return 1; } var EMPTY = {}; function datum(d) { return d.data; } function treeNodes(name, context) { var tree$$1 = data$1.call(context, name); return tree$$1.root && tree$$1.root.lookup || EMPTY; } function treePath(name, source, target) { var nodes = treeNodes(name, this), s = nodes[source], t = nodes[target]; return s && t ? s.path(t).map(datum) : undefined; } function treeAncestors(name, node) { var n = treeNodes(name, this)[node]; return n ? n.ancestors().map(datum) : undefined; } var inrange = function(value, range$$1, left, right) { var r0 = range$$1[0], r1 = range$$1[range$$1.length-1], t; if (r0 > r1) { t = r0; r0 = r1; r1 = t; } left = left === undefined || left; right = right === undefined || right; return (left ? r0 <= value : r0 < value) && (right ? value <= r1 : value < r1); }; var encode$1 = function(item, name, retval) { if (item) { var df = this.context.dataflow, target = item.mark.source; df.pulse(target, df.changeset().encode(item, name)); } return retval !== undefined ? retval : item; }; function equal(a, b) { return a === b || a !== a && b !== b ? true : isArray(a) && isArray(b) && a.length === b.length ? equalArray(a, b) : false; } function equalArray(a, b) { for (var i=0, n=a.length; i<n; ++i) { if (!equal(a[i], b[i])) return false; } return true; } function removePredicate(props) { return function(_$$1) { for (var key$$1 in props) { if (!equal(_$$1[key$$1], props[key$$1])) return false; } return true; }; } var modify = function(name, insert, remove, toggle, modify, values) { var df = this.context.dataflow, data = this.context.data[name], input = data.input, changes = data.changes, stamp = df.stamp(), predicate, key$$1; if (df._trigger === false || !(input.value.length || insert || toggle)) { // nothing to do! return 0; } if (!changes || changes.stamp < stamp) { data.changes = (changes = df.changeset()); changes.stamp = stamp; df.runAfter(function() { data.modified = true; df.pulse(input, changes).run(); }, true); } if (remove) { predicate = remove === true ? truthy : (isArray(remove) || isTuple(remove)) ? remove : removePredicate(remove); changes.remove(predicate); } if (insert) { changes.insert(insert); } if (toggle) { predicate = removePredicate(toggle); if (input.value.some(predicate)) { changes.remove(predicate); } else { changes.insert(toggle); } } if (modify) { for (key$$1 in values) { changes.modify(modify, key$$1, values[key$$1]); } } return 1; }; var BIN = 'bin_'; var INTERSECT = 'intersect'; var UNION = 'union'; var UNIT_INDEX = 'index:unit'; function testPoint(datum, entry) { var fields = entry.fields, values = entry.values, getter = entry.getter || (entry.getter = []), n = fields.length, i = 0, dval; for (; i<n; ++i) { getter[i] = getter[i] || field(fields[i]); dval = getter[i](datum); if (isDate(dval)) dval = toNumber(dval); if (isDate(values[i])) values[i] = toNumber(values[i]); if (entry[BIN + fields[i]]) { if (isDate(values[i][0])) values[i] = values[i].map(toNumber); if (!inrange(dval, values[i], true, false)) return false; } else if (dval !== values[i]) { return false; } } return true; } // TODO: revisit date coercion? // have selections populate with consistent types upon write? function testInterval(datum, entry) { var ivals = entry.intervals, n = ivals.length, i = 0, getter, extent$$1, value; for (; i<n; ++i) { extent$$1 = ivals[i].extent; getter = ivals[i].getter || (ivals[i].getter = field(ivals[i].field)); value = getter(datum); if (!extent$$1 || extent$$1[0] === extent$$1[1]) return false; if (isDate(value)) value = toNumber(value); if (isDate(extent$$1[0])) extent$$1 = ivals[i].extent = extent$$1.map(toNumber); if (isNumber(extent$$1[0]) && !inrange(value, extent$$1)) return false; else if (isString(extent$$1[0]) && extent$$1.indexOf(value) < 0) return false; } return true; } /** * Tests if a tuple is contained within an interactive selection. * @param {string} name - The name of the data set representing the selection. * @param {object} datum - The tuple to test for inclusion. * @param {string} op - The set operation for combining selections. * One of 'intersect' or 'union' (default). * @param {function(object,object):boolean} test - A boolean-valued test * predicate for determining selection status within a single unit chart. * @return {boolean} - True if the datum is in the selection, false otherwise. */ function vlSelection(name, datum, op, test) { var data = this.context.data[name], entries = data ? data.values.value : [], unitIdx = data ? data[UNIT_INDEX] && data[UNIT_INDEX].value : undefined, intersect = op === INTERSECT, n = entries.length, i = 0, entry, miss, count, unit, b; for (; i<n; ++i) { entry = entries[i]; if (unitIdx && intersect) { // multi selections union within the same unit and intersect across units. miss = miss || {}; count = miss[unit=entry.unit] || 0; // if we've already matched this unit, skip. if (count === -1) continue; b = test(datum, entry); miss[unit] = b ? -1 : ++count; // if we match and there are no other units return true // if we've missed against all tuples in this unit return false if (b && unitIdx.size === 1) return true; if (!b && count === unitIdx.get(unit).count) return false; } else { b = test(datum, entry); // if we find a miss and we do require intersection return false // if we find a match and we don't require intersection return true if (intersect ^ b) return b; } } // if intersecting and we made it here, then we saw no misses // if not intersecting, then we saw no matches // if no active selections, return false return n && intersect; } // Assumes point selection tuples are of the form: // {unit: string, encodings: array<string>, fields: array<string>, values: array<*>, bins: object} function vlPoint(name, datum, op) { return vlSelection.call(this, name, datum, op, testPoint); } // Assumes interval selection typles are of the form: // {unit: string, intervals: array<{encoding: string, field:string, extent:array<number>}>} function vlInterval(name, datum, op) { return vlSelection.call(this, name, datum, op, testInterval); } function vlMultiVisitor(name, args, scope, params) { if (args[0].type !== Literal) error$1('First argument to indata must be a string literal.'); var data = args[0].value, // vlMulti, vlMultiDomain have different # of params, but op is always last. op = args.length >= 2 && args[args.length-1].value, field$$1 = 'unit', indexName = indexPrefix + field$$1; if (op === INTERSECT && !params.hasOwnProperty(indexName)) { params[indexName] = scope.getData(data).indataRef(scope, field$$1); } dataVisitor(name, args, scope, params); } /** * Materializes a point selection as a scale domain. * @param {string} name - The name of the dataset representing the selection. * @param {string} [encoding] - A particular encoding channel to materialize. * @param {string} [field] - A particular field to materialize. * @param {string} [op='intersect'] - The set operation for combining selections. * One of 'intersect' (default) or 'union'. * @returns {array} An array of values to serve as a scale domain. */ function vlPointDomain(name, encoding, field$$1, op) { var data = this.context.data[name], entries = data ? data.values.value : [], unitIdx = data ? data[UNIT_INDEX] && data[UNIT_INDEX].value : undefined, entry = entries[0], i = 0, n, index, values, continuous, units; if (!entry) return undefined; for (n = encoding ? entry.encodings.length : entry.fields.length; i<n; ++i) { if ((encoding && entry.encodings[i] === encoding) || (field$$1 && entry.fields[i] === field$$1)) { index = i; continuous = entry[BIN + entry.fields[i]]; break; } } // multi selections union within the same unit and intersect across units. // if we've got only one unit, enforce union for more efficient materialization. if (unitIdx && unitIdx.size === 1) { op = UNION; } if (unitIdx && op === INTERSECT) { units = entries.reduce(function(acc, entry) { var u = acc[entry.unit] || (acc[entry.unit] = []); u.push({unit: entry.unit, value: entry.values[index]}); return acc; }, {}); values = Object.keys(units).map(function(unit) { return { unit: unit, value: continuous ? continuousDomain(units[unit], UNION) : discreteDomain(units[unit], UNION) }; }); } else { values = entries.map(function(entry) { return {unit: entry.unit, value: entry.values[index]}; }); } return continuous ? continuousDomain(values, op) : discreteDomain(values, op); } /** * Materializes an interval selection as a scale domain. * @param {string} name - The name of the dataset representing the selection. * @param {string} [encoding] - A particular encoding channel to materialize. * @param {string} [field] - A particular field to materialize. * @param {string} [op='union'] - The set operation for combining selections. * One of 'intersect' or 'union' (default). * @returns {array} An array of values to serve as a scale domain. */ function vlIntervalDomain(name, encoding, field$$1, op) { var data = this.context.data[name], entries = data ? data.values.value : [], entry = entries[0], i = 0, n, interval, index, values, discrete; if (!entry) return undefined; for (n = entry.intervals.length; i<n; ++i) { interval = entry.intervals[i]; if ((encoding && interval.encoding === encoding) || (field$$1 && interval.field === field$$1)) { if (!interval.extent) return undefined; index = i; discrete = interval.extent.length > 2; break; } } values = entries.reduce(function(acc, entry) { var extent$$1 = entry.intervals[index].extent, value = discrete ? extent$$1.map(function (d) { return {unit: entry.unit, value: d}; }) : {unit: entry.unit, value: extent$$1}; if (discrete) { acc.push.apply(acc, value); } else { acc.push(value); } return acc; }, []); return discrete ? discreteDomain(values, op) : continuousDomain(values, op); } function discreteDomain(entries, op) { var units = {}, count = 0, values = {}, domain = [], i = 0, n = entries.length, entry, unit, v, key$$1; for (; i<n; ++i) { entry = entries[i]; unit = entry.unit; key$$1 = entry.value; if (!units[unit]) units[unit] = ++count; if (!(v = values[key$$1])) { values[key$$1] = v = {value: key$$1, units: {}, count: 0}; } if (!v.units[unit]) v.units[unit] = ++v.count; } for (key$$1 in values) { v = values[key$$1]; if (op === INTERSECT && v.count !== count) continue; domain.push(v.value); } return domain.length ? domain : undefined; } function continuousDomain(entries, op) { var merge$$1 = op === INTERSECT ? intersectInterval : unionInterval, i = 0, n = entries.length, extent$$1, domain, lo, hi; for (; i<n; ++i) { extent$$1 = entries[i].value; if (isDate(extent$$1[0])) extent$$1 = extent$$1.map(toNumber); lo = extent$$1[0]; hi = extent$$1[1]; if (lo > hi) { hi = extent$$1[0]; lo = extent$$1[1]; } domain = domain ? merge$$1(domain, lo, hi) : [lo, hi]; } return domain && domain.length && (+domain[0] !== +domain[1]) ? domain : undefined; } function unionInterval(domain, lo, hi) { if (domain[0] > lo) domain[0] = lo; if (domain[1] < hi) domain[1] = hi; return domain; } function intersectInterval(domain, lo, hi) { if (hi < domain[0] || domain[1] < lo) { return []; } else { if (domain[0] < lo) domain[0] = lo; if (domain[1] > hi) domain[1] = hi; } return domain; } // Expression function context object var functionContext = { random: function() { return exports.random(); }, // override default isArray: isArray, isBoolean: isBoolean, isDate: isDate, isNumber: isNumber, isObject: isObject, isRegExp: isRegExp, isString: isString, isTuple: isTuple, toBoolean: toBoolean, toDate: toDate, toNumber: toNumber, toString: toString, pad: pad, peek: peek, truncate: truncate, rgb: d3Color.rgb, lab: d3Color.lab, hcl: d3Color.hcl, hsl: d3Color.hsl, sequence: d3Array.range, format: format$1, utcFormat: utcFormat$1, utcParse: utcParse$1, timeFormat: timeFormat$1, timeParse: timeParse$1, monthFormat: monthFormat, monthAbbrevFormat: monthAbbrevFormat, dayFormat: dayFormat, dayAbbrevFormat: dayAbbrevFormat, quarter: quarter, utcquarter: utcquarter, warn: warn, info: info, debug: debug, inScope: inScope, clampRange: clampRange, pinchDistance: pinchDistance, pinchAngle: pinchAngle, screen: screen, containerSize: containerSize, windowSize: windowSize, span: span, flush: flush, bandspace: bandspace, inrange: inrange, setdata: setdata, panLinear: panLinear, panLog: panLog, panPow: panPow, zoomLinear: zoomLinear, zoomLog: zoomLog, zoomPow: zoomPow, encode: encode$1, modify: modify }; var eventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y']; var eventPrefix = 'event.vega.'; var thisPrefix = 'this.'; var astVisitors = {}; // AST visitors for dependency analysis function expressionFunction(name, fn, visitor) { if (arguments.length === 1) { return functionContext[name]; } // register with the functionContext functionContext[name] = fn; // if there is an astVisitor register that, too if (visitor) astVisitors[name] = visitor; // if the code generator has already been initialized, // we need to also register the function with it if (codeGenerator) codeGenerator.functions[name] = thisPrefix + name; return this; } // register expression functions with ast visitors expressionFunction('bandwidth', bandwidth, scaleVisitor); expressionFunction('copy', copy, scaleVisitor); expressionFunction('domain', domain, scaleVisitor); expressionFunction('range', range$2, scaleVisitor); expressionFunction('invert', invert, scaleVisitor); expressionFunction('scale', scale$2, scaleVisitor); expressionFunction('gradient', scaleGradient, scaleVisitor); expressionFunction('geoArea', geoArea, scaleVisitor); expressionFunction('geoBounds', geoBounds, scaleVisitor); expressionFunction('geoCentroid', geoCentroid, scaleVisitor); expressionFunction('indata', indata, indataVisitor); expressionFunction('data', data$1, dataVisitor); expressionFunction('vlSingle', vlPoint, dataVisitor); expressionFunction('vlSingleDomain', vlPointDomain, dataVisitor); expressionFunction('vlMulti', vlPoint, vlMultiVisitor); expressionFunction('vlMultiDomain', vlPointDomain, vlMultiVisitor); expressionFunction('vlInterval', vlInterval, dataVisitor); expressionFunction('vlIntervalDomain', vlIntervalDomain, dataVisitor); expressionFunction('treePath', treePath, dataVisitor); expressionFunction('treeAncestors', treeAncestors, dataVisitor); // Build expression function registry function buildFunctions(codegen$$1) { var fn = Functions(codegen$$1); eventFunctions.forEach(function(name) { fn[name] = eventPrefix + name; }); for (var name in functionContext) { fn[name] = thisPrefix + name; } return fn; } // Export code generator and parameters var codegenParams = { blacklist: ['_'], whitelist: ['datum', 'event', 'item'], fieldvar: 'datum', globalvar: function(id$$1) { return '_[' + $$2('$' + id$$1) + ']'; }, functions: buildFunctions, constants: Constants, visitors: astVisitors }; var codeGenerator = codegen(codegenParams); var signalPrefix = '$'; var parseExpression = function(expr, scope, preamble) { var params = {}, ast, gen; // parse the expression to an abstract syntax tree (ast) try { ast = parse$3(expr); } catch (err) { error$1('Expression parse error: ' + $$2(expr)); } // analyze ast function calls for dependencies ast.visit(function visitor(node) { if (node.type !== 'CallExpression') return; var name = node.callee.name, visit = codegenParams.visitors[name]; if (visit) visit(name, node.arguments, scope, params); }); // perform code generation gen = codeGenerator(ast); // collect signal dependencies gen.globals.forEach(function(name) { var signalName = signalPrefix + name; if (!params.hasOwnProperty(signalName) && scope.getSignal(name)) { params[signalName] = scope.signalRef(name); } }); // return generated expression code and dependencies return { $expr: preamble ? preamble + 'return(' + gen.code + ');' : gen.code, $fields: gen.fields, $params: params }; }; var VIEW$1 = 'view'; var SCOPE = 'scope'; var parseStream = function(stream, scope) { return stream.signal ? scope.getSignal(stream.signal).id : stream.scale ? scope.getScale(stream.scale).id : parseStream$1(stream, scope); }; function eventSource(source) { return source === SCOPE ? VIEW$1 : (source || VIEW$1); } function parseStream$1(stream, scope) { var method = stream.merge ? mergeStream : stream.stream ? nestedStream : stream.type ? eventStream : error$1('Invalid stream specification: ' + $$2(stream)); return method(stream, scope); } function mergeStream(stream, scope) { var list = stream.merge.map(function(s) { return parseStream$1(s, scope); }); var entry = streamParameters({merge: list}, stream, scope); return scope.addStream(entry).id; } function nestedStream(stream, scope) { var id$$1 = parseStream$1(stream.stream, scope), entry = streamParameters({stream: id$$1}, stream, scope); return scope.addStream(entry).id; } function eventStream(stream, scope) { var id$$1 = scope.event(eventSource(stream.source), stream.type), entry = streamParameters({stream: id$$1}, stream, scope); return Object.keys(entry).length === 1 ? id$$1 : scope.addStream(entry).id; } function streamParameters(entry, stream, scope) { var param = stream.between; if (param) { if (param.length !== 2) { error$1('Stream "between" parameter must have 2 entries: ' + $$2(stream)); } entry.between = [ parseStream$1(param[0], scope), parseStream$1(param[1], scope) ]; } param = stream.filter ? array(stream.filter) : []; if (stream.marktype || stream.markname || stream.markrole) { // add filter for mark type, name and/or role param.push(filterMark(stream.marktype, stream.markname, stream.markrole)); } if (stream.source === SCOPE) { // add filter to limit events from sub-scope only param.push('inScope(event.item)'); } if (param.length) { entry.filter = parseExpression('(' + param.join(')&&(') + ')').$expr; } if ((param = stream.throttle) != null) { entry.throttle = +param; } if ((param = stream.debounce) != null) { entry.debounce = +param; } if (stream.consume) { entry.consume = true; } return entry; } function filterMark(type, name, role) { var item = 'event.item'; return item + (type && type !== '*' ? '&&' + item + '.mark.marktype===\'' + type + '\'' : '') + (role ? '&&' + item + '.mark.role===\'' + role + '\'' : '') + (name ? '&&' + item + '.mark.name===\'' + name + '\'' : ''); } /** * Parse an event selector string. * Returns an array of event stream definitions. */ var selector = function(selector, source, marks) { DEFAULT_SOURCE = source || VIEW$2; MARKS = marks || DEFAULT_MARKS; return parseMerge(selector.trim()).map(parseSelector); }; var VIEW$2 = 'view'; var LBRACK = '['; var RBRACK = ']'; var LBRACE = '{'; var RBRACE = '}'; var COLON = ':'; var COMMA = ','; var NAME = '@'; var GT = '>'; var ILLEGAL$1 = /[[\]{}]/; var DEFAULT_SOURCE; var MARKS; var DEFAULT_MARKS = { '*': 1, arc: 1, area: 1, group: 1, image: 1, line: 1, path: 1, rect: 1, rule: 1, shape: 1, symbol: 1, text: 1, trail: 1 }; function isMarkType(type) { return MARKS.hasOwnProperty(type); } function find(s, i, endChar, pushChar, popChar) { var count = 0, n = s.length, c; for (; i<n; ++i) { c = s[i]; if (!count && c === endChar) return i; else if (popChar && popChar.indexOf(c) >= 0) --count; else if (pushChar && pushChar.indexOf(c) >= 0) ++count; } return i; } function parseMerge(s) { var output = [], start = 0, n = s.length, i = 0; while (i < n) { i = find(s, i, COMMA, LBRACK + LBRACE, RBRACK + RBRACE); output.push(s.substring(start, i).trim()); start = ++i; } if (output.length === 0) { throw 'Empty event selector: ' + s; } return output; } function parseSelector(s) { return s[0] === '[' ? parseBetween(s) : parseStream$2(s); } function parseBetween(s) { var n = s.length, i = 1, b, stream; i = find(s, i, RBRACK, LBRACK, RBRACK); if (i === n) { throw 'Empty between selector: ' + s; } b = parseMerge(s.substring(1, i)); if (b.length !== 2) { throw 'Between selector must have two elements: ' + s; } s = s.slice(i + 1).trim(); if (s[0] !== GT) { throw 'Expected \'>\' after between selector: ' + s; } b = b.map(parseSelector); stream = parseSelector(s.slice(1).trim()); if (stream.between) { return { between: b, stream: stream }; } else { stream.between = b; } return stream; } function parseStream$2(s) { var stream = {source: DEFAULT_SOURCE}, source = [], throttle = [0, 0], markname = 0, start = 0, n = s.length, i = 0, j, filter; // extract throttle from end if (s[n-1] === RBRACE) { i = s.lastIndexOf(LBRACE); if (i >= 0) { try { throttle = parseThrottle(s.substring(i+1, n-1)); } catch (e) { throw 'Invalid throttle specification: ' + s; } s = s.slice(0, i).trim(); n = s.length; } else throw 'Unmatched right brace: ' + s; i = 0; } if (!n) throw s; // set name flag based on first char if (s[0] === NAME) markname = ++i; // extract first part of multi-part stream selector j = find(s, i, COLON); if (j < n) { source.push(s.substring(start, j).trim()); start = i = ++j; } // extract remaining part of stream selector i = find(s, i, LBRACK); if (i === n) { source.push(s.substring(start, n).trim()); } else { source.push(s.substring(start, i).trim()); filter = []; start = ++i; if (start === n) throw 'Unmatched left bracket: ' + s; } // extract filters while (i < n) { i = find(s, i, RBRACK); if (i === n) throw 'Unmatched left bracket: ' + s; filter.push(s.substring(start, i).trim()); if (i < n-1 && s[++i] !== LBRACK) throw 'Expected left bracket: ' + s; start = ++i; } // marshall event stream specification if (!(n = source.length) || ILLEGAL$1.test(source[n-1])) { throw 'Invalid event selector: ' + s; } if (n > 1) { stream.type = source[1]; if (markname) { stream.markname = source[0].slice(1); } else if (isMarkType(source[0])) { stream.marktype = source[0]; } else { stream.source = source[0]; } } else { stream.type = source[0]; } if (stream.type.slice(-1) === '!') { stream.consume = true; stream.type = stream.type.slice(0, -1); } if (filter != null) stream.filter = filter; if (throttle[0]) stream.throttle = throttle[0]; if (throttle[1]) stream.debounce = throttle[1]; return stream; } function parseThrottle(s) { var a = s.split(COMMA); if (!s.length || a.length > 2) throw s; return a.map(function(_$$1) { var x = +_$$1; if (x !== x) throw s; return x; }); } var preamble = 'var datum=event.item&&event.item.datum;'; var parseUpdate = function(spec, scope, target) { var events = spec.events, update = spec.update, encode = spec.encode, sources = [], value = '', entry; if (!events) { error$1('Signal update missing events specification.'); } // interpret as an event selector string if (isString(events)) { events = selector(events); } // separate event streams from signal updates events = array(events).filter(function(stream) { if (stream.signal || stream.scale) { sources.push(stream); return 0; } else { return 1; } }); // merge event streams, include as source if (events.length) { sources.push(events.length > 1 ? {merge: events} : events[0]); } if (encode != null) { if (update) error$1('Signal encode and update are mutually exclusive.'); update = 'encode(item(),' + $$2(encode) + ')'; } // resolve update value value = isString(update) ? parseExpression(update, scope, preamble) : update.expr != null ? parseExpression(update.expr, scope, preamble) : update.value != null ? update.value : update.signal != null ? { $expr: '_.value', $params: {value: scope.signalRef(update.signal)} } : error$1('Invalid signal update specification.'); entry = { target: target, update: value }; if (spec.force) { entry.options = {force: true}; } sources.forEach(function(source) { source = {source: parseStream(source, scope)}; scope.addUpdate(extend(source, entry)); }); }; var parseSignalUpdates = function(signal, scope) { var op = scope.getSignal(signal.name); if (signal.update) { var expr = parseExpression(signal.update, scope); op.update = expr.$expr; op.params = expr.$params; } if (signal.on) { signal.on.forEach(function(_$$1) { parseUpdate(_$$1, scope, op.id); }); } }; function Entry(type, value, params, parent) { this.id = -1; this.type = type; this.value = value; this.params = params; if (parent) this.parent = parent; } function entry(type, value, params, parent) { return new Entry(type, value, params, parent); } function operator(value, params) { return entry('operator', value, params); } // ----- function ref(op) { var ref = {$ref: op.id}; // if operator not yet registered, cache ref to resolve later if (op.id < 0) (op.refs = op.refs || []).push(ref); return ref; } var tupleidRef = { $tupleid: 1, toString: function() { return ':_tupleid_:'; } }; function fieldRef$1(field$$1, name) { return name ? {$field: field$$1, $name: name} : {$field: field$$1}; } var keyFieldRef = fieldRef$1('key'); function compareRef(fields, orders) { return {$compare: fields, $order: orders}; } function keyRef(fields, flat) { var ref = {$key: fields}; if (flat) ref.$flat = true; return ref; } // ----- var Ascending = 'ascending'; var Descending = 'descending'; function sortKey(sort) { return !isObject(sort) ? '' : (sort.order === Descending ? '-' : '+') + aggrField(sort.op, sort.field); } function aggrField(op, field$$1) { return (op && op.signal ? '$' + op.signal : op || '') + (op && field$$1 ? '_' : '') + (field$$1 && field$$1.signal ? '$' + field$$1.signal : field$$1 || ''); } // ----- function isSignal(_$$1) { return _$$1 && _$$1.signal; } function value(specValue, defaultValue) { return specValue != null ? specValue : defaultValue; } function transform$2(name) { return function(params, value$$1, parent) { return entry(name, value$$1, params || undefined, parent); }; } var Aggregate$1 = transform$2('aggregate'); var AxisTicks$1 = transform$2('axisticks'); var Bound$1 = transform$2('bound'); var Collect$1 = transform$2('collect'); var Compare$1 = transform$2('compare'); var DataJoin$1 = transform$2('datajoin'); var Encode$1 = transform$2('encode'); var Facet$1 = transform$2('facet'); var Field$1 = transform$2('field'); var Key$1 = transform$2('key'); var LegendEntries$1 = transform$2('legendentries'); var Mark$1 = transform$2('mark'); var MultiExtent$1 = transform$2('multiextent'); var MultiValues$1 = transform$2('multivalues'); var Overlap$1 = transform$2('overlap'); var Params$2 = transform$2('params'); var PreFacet$1 = transform$2('prefacet'); var Projection$1 = transform$2('projection'); var Proxy$1 = transform$2('proxy'); var Relay$1 = transform$2('relay'); var Render$1 = transform$2('render'); var Scale$1 = transform$2('scale'); var Sieve$1 = transform$2('sieve'); var SortItems$1 = transform$2('sortitems'); var ViewLayout$1 = transform$2('viewlayout'); var Values$1 = transform$2('values'); var FIELD_REF_ID = 0; var types = [ 'identity', 'ordinal', 'band', 'point', 'bin-linear', 'bin-ordinal', 'linear', 'pow', 'sqrt', 'log', 'sequential', 'time', 'utc', 'quantize', 'quantile', 'threshold' ]; var allTypes = toSet(types); var ordinalTypes = toSet(types.slice(1, 6)); function isOrdinal(type) { return ordinalTypes.hasOwnProperty(type); } function isQuantile(type) { return type === 'quantile'; } function initScale(spec, scope) { var type = spec.type || 'linear'; if (!allTypes.hasOwnProperty(type)) { error$1('Unrecognized scale type: ' + $$2(type)); } scope.addScale(spec.name, { type: type, domain: undefined }); } function parseScale(spec, scope) { var params = scope.getScale(spec.name).params, key$$1; params.domain = parseScaleDomain(spec.domain, spec, scope); if (spec.range != null) { params.range = parseScaleRange(spec, scope, params); } if (spec.interpolate != null) { parseScaleInterpolate(spec.interpolate, params); } if (spec.nice != null) { parseScaleNice(spec.nice, params); } for (key$$1 in spec) { if (params.hasOwnProperty(key$$1) || key$$1 === 'name') continue; params[key$$1] = parseLiteral(spec[key$$1], scope); } } function parseLiteral(v, scope) { return !isObject(v) ? v : v.signal ? scope.signalRef(v.signal) : error$1('Unsupported object: ' + $$2(v)); } function parseArray(v, scope) { return v.signal ? scope.signalRef(v.signal) : v.map(function(v) { return parseLiteral(v, scope); }); } function dataLookupError(name) { error$1('Can not find data set: ' + $$2(name)); } // -- SCALE DOMAIN ---- function parseScaleDomain(domain, spec, scope) { if (!domain) { if (spec.domainMin != null || spec.domainMax != null) { error$1('No scale domain defined for domainMin/domainMax to override.'); } return; // default domain } return domain.signal ? scope.signalRef(domain.signal) : (isArray(domain) ? explicitDomain : domain.fields ? multipleDomain : singularDomain)(domain, spec, scope); } function explicitDomain(domain, spec, scope) { return domain.map(function(v) { return parseLiteral(v, scope); }); } function singularDomain(domain, spec, scope) { var data = scope.getData(domain.data); if (!data) dataLookupError(domain.data); return isOrdinal(spec.type) ? data.valuesRef(scope, domain.field, parseSort(domain.sort, false)) : isQuantile(spec.type) ? data.domainRef(scope, domain.field) : data.extentRef(scope, domain.field); } function multipleDomain(domain, spec, scope) { var data = domain.data, fields = domain.fields.reduce(function(dom, d) { d = isString(d) ? {data: data, field: d} : (isArray(d) || d.signal) ? fieldRef(d, scope) : d; dom.push(d); return dom; }, []); return (isOrdinal(spec.type) ? ordinalMultipleDomain : isQuantile(spec.type) ? quantileMultipleDomain : numericMultipleDomain)(domain, scope, fields); } function fieldRef(data, scope) { var name = '_:vega:_' + (FIELD_REF_ID++), coll = Collect$1({}); if (isArray(data)) { coll.value = {$ingest: data}; } else if (data.signal) { var code = 'setdata(' + $$2(name) + ',' + data.signal + ')'; coll.params.input = scope.signalRef(code); } scope.addDataPipeline(name, [coll, Sieve$1({})]); return {data: name, field: 'data'}; } function ordinalMultipleDomain(domain, scope, fields) { var counts, a, c, v; // get value counts for each domain field counts = fields.map(function(f) { var data = scope.getData(f.data); if (!data) dataLookupError(f.data); return data.countsRef(scope, f.field); }); // sum counts from all fields a = scope.add(Aggregate$1({ groupby: keyFieldRef, ops:['sum'], fields: [scope.fieldRef('count')], as:['count'], pulse: counts })); // collect aggregate output c = scope.add(Collect$1({pulse: ref(a)})); // extract values for combined domain v = scope.add(Values$1({ field: keyFieldRef, sort: scope.sortRef(parseSort(domain.sort, true)), pulse: ref(c) })); return ref(v); } function parseSort(sort, multidomain) { if (sort) { if (!sort.field && !sort.op) { if (isObject(sort)) sort.field = 'key'; else sort = {field: 'key'}; } else if (!sort.field && sort.op !== 'count') { error$1('No field provided for sort aggregate op: ' + sort.op); } else if (multidomain && sort.field) { error$1('Multiple domain scales can not sort by field.'); } else if (multidomain && sort.op && sort.op !== 'count') { error$1('Multiple domain scales support op count only.'); } } return sort; } function quantileMultipleDomain(domain, scope, fields) { // get value arrays for each domain field var values = fields.map(function(f) { var data = scope.getData(f.data); if (!data) dataLookupError(f.data); return data.domainRef(scope, f.field); }); // combine value arrays return ref(scope.add(MultiValues$1({values: values}))); } function numericMultipleDomain(domain, scope, fields) { // get extents for each domain field var extents = fields.map(function(f) { var data = scope.getData(f.data); if (!data) dataLookupError(f.data); return data.extentRef(scope, f.field); }); // combine extents return ref(scope.add(MultiExtent$1({extents: extents}))); } // -- SCALE NICE ----- function parseScaleNice(nice, params) { params.nice = isObject(nice) ? { interval: parseLiteral(nice.interval), step: parseLiteral(nice.step) } : parseLiteral(nice); } // -- SCALE INTERPOLATION ----- function parseScaleInterpolate(interpolate$$1, params) { params.interpolate = parseLiteral(interpolate$$1.type || interpolate$$1); if (interpolate$$1.gamma != null) { params.interpolateGamma = parseLiteral(interpolate$$1.gamma); } } // -- SCALE RANGE ----- function parseScaleRange(spec, scope, params) { var range$$1 = spec.range, config = scope.config.range; if (range$$1.signal) { return scope.signalRef(range$$1.signal); } else if (isString(range$$1)) { if (config && config.hasOwnProperty(range$$1)) { spec = extend({}, spec, {range: config[range$$1]}); return parseScaleRange(spec, scope, params); } else if (range$$1 === 'width') { range$$1 = [0, {signal: 'width'}]; } else if (range$$1 === 'height') { range$$1 = isOrdinal(spec.type) ? [0, {signal: 'height'}] : [{signal: 'height'}, 0]; } else { error$1('Unrecognized scale range value: ' + $$2(range$$1)); } } else if (range$$1.scheme) { params.scheme = parseLiteral(range$$1.scheme, scope); if (range$$1.extent) params.schemeExtent = parseArray(range$$1.extent, scope); if (range$$1.count) params.schemeCount = parseLiteral(range$$1.count, scope); return; } else if (range$$1.step) { params.rangeStep = parseLiteral(range$$1.step, scope); return; } else if (isOrdinal(spec.type) && !isArray(range$$1)) { return parseScaleDomain(range$$1, spec, scope); } else if (!isArray(range$$1)) { error$1('Unsupported range type: ' + $$2(range$$1)); } return range$$1.map(function(v) { return parseLiteral(v, scope); }); } var parseProjection = function(proj, scope) { var params = {}; for (var name in proj) { if (name === 'name') continue; params[name] = parseParameter(proj[name], scope); } scope.addProjection(proj.name, params); }; function parseParameter(_$$1, scope) { return isArray(_$$1) ? _$$1.map(function(_$$1) { return parseParameter(_$$1, scope); }) : !isObject(_$$1) ? _$$1 : _$$1.signal ? scope.signalRef(_$$1.signal) : error$1('Unsupported parameter object: ' + $$2(_$$1)); } var Top$1 = 'top'; var Left$1 = 'left'; var Right$1 = 'right'; var Bottom$1 = 'bottom'; var Index = 'index'; var Label = 'label'; var Offset = 'offset'; var Perc = 'perc'; var Size = 'size'; var Total = 'total'; var Value = 'value'; var GuideLabelStyle = 'guide-label'; var GuideTitleStyle = 'guide-title'; var GroupTitleStyle = 'group-title'; var LegendScales = [ 'shape', 'size', 'fill', 'stroke', 'strokeDash', 'opacity' ]; var Skip = { name: 1, interactive: 1 }; var Skip$1 = toSet(['rule']); var Swap = toSet(['group', 'image', 'rect']); var adjustSpatial = function(encode, marktype) { var code = ''; if (Skip$1[marktype]) return code; if (encode.x2) { if (encode.x) { if (Swap[marktype]) { code += 'if(o.x>o.x2)$=o.x,o.x=o.x2,o.x2=$;'; } code += 'o.width=o.x2-o.x;'; } else { code += 'o.x=o.x2-(o.width||0);'; } } if (encode.xc) { code += 'o.x=o.xc-(o.width||0)/2;'; } if (encode.y2) { if (encode.y) { if (Swap[marktype]) { code += 'if(o.y>o.y2)$=o.y,o.y=o.y2,o.y2=$;'; } code += 'o.height=o.y2-o.y;'; } else { code += 'o.y=o.y2-(o.height||0);'; } } if (encode.yc) { code += 'o.y=o.yc-(o.height||0)/2;'; } return code; }; var color$1 = function(enc, scope, params, fields) { function color(type, x, y, z) { var a = entry$1(null, x, scope, params, fields), b = entry$1(null, y, scope, params, fields), c = entry$1(null, z, scope, params, fields); return 'this.' + type + '(' + [a, b, c].join(',') + ').toString()'; } return (enc.c) ? color('hcl', enc.h, enc.c, enc.l) : (enc.h || enc.s) ? color('hsl', enc.h, enc.s, enc.l) : (enc.l || enc.a) ? color('lab', enc.l, enc.a, enc.b) : (enc.r || enc.g || enc.b) ? color('rgb', enc.r, enc.g, enc.b) : null; }; var expression = function(code, scope, params, fields) { var expr = parseExpression(code, scope); expr.$fields.forEach(function(name) { fields[name] = 1; }); extend(params, expr.$params); return expr.$expr; }; var field$1 = function(ref, scope, params, fields) { return resolve$1(isObject(ref) ? ref : {datum: ref}, scope, params, fields); }; function resolve$1(ref, scope, params, fields) { var object, level, field$$1; if (ref.signal) { object = 'datum'; field$$1 = expression(ref.signal, scope, params, fields); } else if (ref.group || ref.parent) { level = Math.max(1, ref.level || 1); object = 'item'; while (level-- > 0) { object += '.mark.group'; } if (ref.parent) { field$$1 = ref.parent; object += '.datum'; } else { field$$1 = ref.group; } } else if (ref.datum) { object = 'datum'; field$$1 = ref.datum; } else { error$1('Invalid field reference: ' + $$2(ref)); } if (!ref.signal) { if (isString(field$$1)) { fields[field$$1] = 1; // TODO review field tracking? field$$1 = splitAccessPath(field$$1).map($$2).join(']['); } else { field$$1 = resolve$1(field$$1, scope, params, fields); } } return object + '[' + field$$1 + ']'; } var scale$3 = function(enc, value, scope, params, fields) { var scale = getScale$1(enc.scale, scope, params, fields), interp, func, flag; if (enc.range != null) { // pull value from scale range interp = +enc.range; func = scale + '.range()'; value = (interp === 0) ? (func + '[0]') : '($=' + func + ',' + ((interp === 1) ? '$[$.length-1]' : '$[0]+' + interp + '*($[$.length-1]-$[0])') + ')'; } else { // run value through scale and/or pull scale bandwidth if (value !== undefined) value = scale + '(' + value + ')'; if (enc.band && (flag = hasBandwidth(enc.scale, scope))) { func = scale + '.bandwidth'; interp = +enc.band; interp = func + '()' + (interp===1 ? '' : '*' + interp); // if we don't know the scale type, check for bandwidth if (flag < 0) interp = '(' + func + '?' + interp + ':0)'; value = (value ? value + '+' : '') + interp; if (enc.extra) { // include logic to handle extraneous elements value = '(datum.extra?' + scale + '(datum.extra.value):' + value + ')'; } } if (value == null) value = '0'; } return value; }; function hasBandwidth(name, scope) { if (!isString(name)) return -1; var type = scope.scaleType(name); return type === 'band' || type === 'point' ? 1 : 0; } function getScale$1(name, scope, params, fields) { var scaleName; if (isString(name)) { // direct scale lookup; add scale as parameter scaleName = scalePrefix + name; if (!params.hasOwnProperty(scaleName)) { params[scaleName] = scope.scaleRef(name); } scaleName = $$2(scaleName); } else { // indirect scale lookup; add all scales as parameters for (scaleName in scope.scales) { params[scalePrefix + scaleName] = scope.scaleRef(scaleName); } scaleName = $$2(scalePrefix) + '+' + (name.signal ? '(' + expression(name.signal, scope, params, fields) + ')' : field$1(name, scope, params, fields)); } return '_[' + scaleName + ']'; } var gradient$1 = function(enc, scope, params, fields) { return 'this.gradient(' + getScale$1(enc.gradient, scope, params, fields) + ',' + $$2(enc.start) + ',' + $$2(enc.stop) + ',' + $$2(enc.count) + ')'; }; var property = function(property, scope, params, fields) { return isObject(property) ? '(' + entry$1(null, property, scope, params, fields) + ')' : property; }; var entry$1 = function(channel, enc, scope, params, fields) { if (enc.gradient != null) { return gradient$1(enc, scope, params, fields); } var value = enc.signal ? expression(enc.signal, scope, params, fields) : enc.color ? color$1(enc.color, scope, params, fields) : enc.field != null ? field$1(enc.field, scope, params, fields) : enc.value !== undefined ? $$2(enc.value) : undefined; if (enc.scale != null) { value = scale$3(enc, value, scope, params, fields); } if (value === undefined) { value = null; } if (enc.exponent != null) { value = 'Math.pow(' + value + ',' + property(enc.exponent, scope, params, fields) + ')'; } if (enc.mult != null) { value += '*' + property(enc.mult, scope, params, fields); } if (enc.offset != null) { value += '+' + property(enc.offset, scope, params, fields); } if (enc.round) { value = 'Math.round(' + value + ')'; } return value; }; var set$2 = function(obj, key$$1, value) { return obj + '[' + $$2(key$$1) + ']=' + value + ';'; }; var rule$1 = function(channel, rules, scope, params, fields) { var code = ''; rules.forEach(function(rule) { var value = entry$1(channel, rule, scope, params, fields); code += rule.test ? expression(rule.test, scope, params, fields) + '?' + value + ':' : value; }); return set$2('o', channel, code); }; function parseEncode(encode, marktype, params, scope) { var fields = {}, code = 'var o=item,datum=o.datum,$;', channel, enc, value; for (channel in encode) { enc = encode[channel]; if (isArray(enc)) { // rule code += rule$1(channel, enc, scope, params, fields); } else { value = entry$1(channel, enc, scope, params, fields); code += set$2('o', channel, value); } } code += adjustSpatial(encode, marktype); code += 'return 1;'; return { $expr: code, $fields: Object.keys(fields), $output: Object.keys(encode) }; } var MarkRole = 'mark'; var FrameRole$1 = 'frame'; var ScopeRole$1 = 'scope'; var AxisRole$2 = 'axis'; var AxisDomainRole = 'axis-domain'; var AxisGridRole = 'axis-grid'; var AxisLabelRole = 'axis-label'; var AxisTickRole = 'axis-tick'; var AxisTitleRole = 'axis-title'; var LegendRole$2 = 'legend'; var LegendEntryRole = 'legend-entry'; var LegendGradientRole = 'legend-gradient'; var LegendLabelRole = 'legend-label'; var LegendSymbolRole = 'legend-symbol'; var LegendTitleRole = 'legend-title'; var TitleRole$1 = 'title'; function encoder(_$$1) { return isObject(_$$1) ? _$$1 : {value: _$$1}; } function addEncode(object, name, value) { if (value != null) { object[name] = isObject(value) && !isArray(value) ? value : {value: value}; return 1; } else { return 0; } } function extendEncode(encode, extra, skip) { for (var name in extra) { if (skip && skip.hasOwnProperty(name)) continue; encode[name] = extend(encode[name] || {}, extra[name]); } return encode; } function encoders(encode, type, role, style, scope, params) { var enc, key$$1; params = params || {}; params.encoders = {$encode: (enc = {})}; encode = applyDefaults(encode, type, role, style, scope.config); for (key$$1 in encode) { enc[key$$1] = parseEncode(encode[key$$1], type, params, scope); } return params; } function applyDefaults(encode, type, role, style, config) { var enter = {}, key$$1, skip, props; // ignore legend and axis if (role == 'legend' || String(role).indexOf('axis') === 0) { role = null; } // resolve mark config props = role === FrameRole$1 ? config.group : (role === MarkRole) ? extend({}, config.mark, config[type]) : null; for (key$$1 in props) { // do not apply defaults if relevant fields are defined skip = has(key$$1, encode) || (key$$1 === 'fill' || key$$1 === 'stroke') && (has('fill', encode) || has('stroke', encode)); if (!skip) enter[key$$1] = {value: props[key$$1]}; } // resolve styles, apply with increasing precedence array(style).forEach(function(name) { var props = config.style && config.style[name]; for (var key$$1 in props) { if (!has(key$$1, encode)) { enter[key$$1] = {value: props[key$$1]}; } } }); encode = extend({}, encode); // defensive copy encode.enter = extend(enter, encode.enter); return encode; } function has(key$$1, encode) { return encode && ( (encode.enter && encode.enter[key$$1]) || (encode.update && encode.update[key$$1]) ); } var guideMark = function(type, role, style, key, dataRef, encode, extras) { return { type: type, name: extras ? extras.name : undefined, role: role, style: (extras && extras.style) || style, key: key, from: dataRef, interactive: !!(extras && extras.interactive), encode: extendEncode(encode, extras, Skip) }; }; var GroupMark = 'group'; var RectMark = 'rect'; var RuleMark = 'rule'; var SymbolMark = 'symbol'; var TextMark = 'text'; var legendGradient = function(spec, scale, config, userEncode) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero, x: zero, y: zero }; addEncode(enter, 'width', config.gradientWidth); addEncode(enter, 'height', config.gradientHeight); addEncode(enter, 'stroke', config.gradientStrokeColor); addEncode(enter, 'strokeWidth', config.gradientStrokeWidth); encode.exit = { opacity: zero }; encode.update = update = { x: zero, y: zero, fill: {gradient: scale}, opacity: {value: 1} }; addEncode(update, 'width', config.gradientWidth); addEncode(update, 'height', config.gradientHeight); return guideMark(RectMark, LegendGradientRole, null, undefined, undefined, encode, userEncode); }; var alignExpr = 'datum.' + Perc + '<=0?"left"' + ':datum.' + Perc + '>=1?"right":"center"'; var legendGradientLabels = function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero }; addEncode(enter, 'fill', config.labelColor); addEncode(enter, 'font', config.labelFont); addEncode(enter, 'fontSize', config.labelFontSize); addEncode(enter, 'fontWeight', config.labelFontWeight); addEncode(enter, 'baseline', config.gradientLabelBaseline); addEncode(enter, 'limit', config.gradientLabelLimit); encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1}, text: {field: Label} }; enter.x = update.x = { field: Perc, mult: config.gradientWidth }; enter.y = update.y = { value: config.gradientHeight, offset: config.gradientLabelOffset }; enter.align = update.align = {signal: alignExpr}; return guideMark(TextMark, LegendLabelRole, GuideLabelStyle, Perc, dataRef, encode, userEncode); }; var legendLabels = function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero }; addEncode(enter, 'align', config.labelAlign); addEncode(enter, 'baseline', config.labelBaseline); addEncode(enter, 'fill', config.labelColor); addEncode(enter, 'font', config.labelFont); addEncode(enter, 'fontSize', config.labelFontSize); addEncode(enter, 'fontWeight', config.labelFontWeight); addEncode(enter, 'limit', config.labelLimit); encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1}, text: {field: Label} }; enter.x = update.x = { field: Offset, offset: config.labelOffset }; enter.y = update.y = { field: Size, mult: 0.5, offset: { field: Total, offset: { field: {group: 'entryPadding'}, mult: {field: Index} } } }; return guideMark(TextMark, LegendLabelRole, GuideLabelStyle, Value, dataRef, encode, userEncode); }; var legendSymbols = function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero }; addEncode(enter, 'shape', config.symbolType); addEncode(enter, 'size', config.symbolSize); addEncode(enter, 'strokeWidth', config.symbolStrokeWidth); if (!spec.fill) { addEncode(enter, 'fill', config.symbolFillColor); addEncode(enter, 'stroke', config.symbolStrokeColor); } encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; enter.x = update.x = { field: Offset, mult: 0.5 }; enter.y = update.y = { field: Size, mult: 0.5, offset: { field: Total, offset: { field: {group: 'entryPadding'}, mult: {field: Index} } } }; LegendScales.forEach(function(scale) { if (spec[scale]) { update[scale] = enter[scale] = {scale: spec[scale], field: Value}; } }); return guideMark(SymbolMark, LegendSymbolRole, null, Value, dataRef, encode, userEncode); }; var legendTitle = function(spec, config, userEncode, dataRef) { var zero = {value: 0}, title = spec.title, encode = {}, enter; encode.enter = enter = { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, opacity: zero }; addEncode(enter, 'align', config.titleAlign); addEncode(enter, 'baseline', config.titleBaseline); addEncode(enter, 'fill', config.titleColor); addEncode(enter, 'font', config.titleFont); addEncode(enter, 'fontSize', config.titleFontSize); addEncode(enter, 'fontWeight', config.titleFontWeight); addEncode(enter, 'limit', config.titleLimit); encode.exit = { opacity: zero }; encode.update = { opacity: {value: 1}, text: title && title.signal ? {signal: title.signal} : {value: title + ''} }; return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode); }; var guideGroup = function(role, style, name, dataRef, interactive, encode, marks) { return { type: GroupMark, name: name, role: role, style: style, from: dataRef, interactive: interactive, encode: encode, marks: marks }; }; var role = function(spec) { var role = spec.role || ''; return (!role.indexOf('axis') || !role.indexOf('legend')) ? role : spec.type === GroupMark ? ScopeRole$1 : (role || MarkRole); }; var definition$1 = function(spec) { return { clip: spec.clip || false, interactive: spec.interactive === false ? false : true, marktype: spec.type, name: spec.name || undefined, role: spec.role || role(spec), zindex: +spec.zindex || undefined }; }; /** * Parse a data transform specification. */ var parseTransform = function(spec, scope) { var def = definition(spec.type); if (!def) error$1('Unrecognized transform type: ' + $$2(spec.type)); var t = entry(def.type.toLowerCase(), null, parseParameters(def, spec, scope)); if (spec.signal) scope.addSignal(spec.signal, scope.proxy(t)); t.metadata = def.metadata || {}; return t; }; /** * Parse all parameters of a data transform. */ function parseParameters(def, spec, scope) { var params = {}, pdef, i, n; for (i=0, n=def.params.length; i<n; ++i) { pdef = def.params[i]; params[pdef.name] = parseParameter$1(pdef, spec, scope); } return params; } /** * Parse a data transform parameter. */ function parseParameter$1(def, spec, scope) { var type = def.type, value$$1 = spec[def.name]; if (type === 'index') { return parseIndexParameter(def, spec, scope); } else if (value$$1 === undefined) { if (def.required) { error$1('Missing required ' + $$2(spec.type) + ' parameter: ' + $$2(def.name)); } return; } else if (type === 'param') { return parseSubParameters(def, spec, scope); } else if (type === 'projection') { return scope.projectionRef(spec[def.name]); } return def.array && !isSignal(value$$1) ? value$$1.map(function(v) { return parameterValue(def, v, scope); }) : parameterValue(def, value$$1, scope); } /** * Parse a single parameter value. */ function parameterValue(def, value$$1, scope) { var type = def.type; if (isSignal(value$$1)) { return isExpr(type) ? error$1('Expression references can not be signals.') : isField(type) ? scope.fieldRef(value$$1) : isCompare(type) ? scope.compareRef(value$$1) : scope.signalRef(value$$1.signal); } else { var expr = def.expr || isField(type); return expr && outerExpr(value$$1) ? parseExpression(value$$1.expr, scope) : expr && outerField(value$$1) ? fieldRef$1(value$$1.field) : isExpr(type) ? parseExpression(value$$1, scope) : isData(type) ? ref(scope.getData(value$$1).values) : isField(type) ? fieldRef$1(value$$1) : isCompare(type) ? scope.compareRef(value$$1) : value$$1; } } /** * Parse parameter for accessing an index of another data set. */ function parseIndexParameter(def, spec, scope) { if (!isString(spec.from)) { error$1('Lookup "from" parameter must be a string literal.'); } return scope.getData(spec.from).lookupRef(scope, spec.key); } /** * Parse a parameter that contains one or more sub-parameter objects. */ function parseSubParameters(def, spec, scope) { var value$$1 = spec[def.name]; if (def.array) { if (!isArray(value$$1)) { // signals not allowed! error$1('Expected an array of sub-parameters. Instead: ' + $$2(value$$1)); } return value$$1.map(function(v) { return parseSubParameter(def, v, scope); }); } else { return parseSubParameter(def, value$$1, scope); } } /** * Parse a sub-parameter object. */ function parseSubParameter(def, value$$1, scope) { var params, pdef, k, i, n; // loop over defs to find matching key for (i=0, n=def.params.length; i<n; ++i) { pdef = def.params[i]; for (k in pdef.key) { if (pdef.key[k] !== value$$1[k]) { pdef = null; break; } } if (pdef) break; } // raise error if matching key not found if (!pdef) error$1('Unsupported parameter: ' + $$2(value$$1)); // parse params, create Params transform, return ref params = extend(parseParameters(pdef, value$$1, scope), pdef.key); return ref(scope.add(Params$2(params))); } // -- Utilities ----- function outerExpr(_$$1) { return _$$1 && _$$1.expr; } function outerField(_$$1) { return _$$1 && _$$1.field; } function isData(_$$1) { return _$$1 === 'data'; } function isExpr(_$$1) { return _$$1 === 'expr'; } function isField(_$$1) { return _$$1 === 'field'; } function isCompare(_$$1) { return _$$1 === 'compare' } var parseData = function(from, group, scope) { var facet, key$$1, op, dataRef, parent; // if no source data, generate singleton datum if (!from) { dataRef = ref(scope.add(Collect$1(null, [{}]))); } // if faceted, process facet specification else if (facet = from.facet) { if (!group) error$1('Only group marks can be faceted.'); // use pre-faceted source data, if available if (facet.field != null) { dataRef = parent = ref(scope.getData(facet.data).output); } else { // generate facet aggregates if no direct data specification if (!from.data) { op = parseTransform(extend({ type: 'aggregate', groupby: array(facet.groupby) }, facet.aggregate), scope); op.params.key = scope.keyRef(facet.groupby); op.params.pulse = ref(scope.getData(facet.data).output); dataRef = parent = ref(scope.add(op)); } else { parent = ref(scope.getData(from.data).aggregate); } key$$1 = scope.keyRef(facet.groupby, true); } } // if not yet defined, get source data reference if (!dataRef) { dataRef = from.$ref ? from : ref(scope.getData(from.data).output); } return { key: key$$1, pulse: dataRef, parent: parent }; }; function DataScope(scope, input, output, values, aggr) { this.scope = scope; // parent scope object this.input = input; // first operator in pipeline (tuple input) this.output = output; // last operator in pipeline (tuple output) this.values = values; // operator for accessing tuples (but not tuple flow) // last aggregate in transform pipeline this.aggregate = aggr; // lookup table of field indices this.index = {}; } DataScope.fromEntries = function(scope, entries) { var n = entries.length, i = 1, input = entries[0], values = entries[n-1], output = entries[n-2], aggr = null; // add operator entries to this scope, wire up pulse chain scope.add(entries[0]); for (; i<n; ++i) { entries[i].params.pulse = ref(entries[i-1]); scope.add(entries[i]); if (entries[i].type === 'aggregate') aggr = entries[i]; } return new DataScope(scope, input, output, values, aggr); }; var prototype$82 = DataScope.prototype; prototype$82.countsRef = function(scope, field$$1, sort) { var ds = this, cache = ds.counts || (ds.counts = {}), k = fieldKey(field$$1), v, a, p; if (k != null) { scope = ds.scope; v = cache[k]; } if (!v) { p = { groupby: scope.fieldRef(field$$1, 'key'), pulse: ref(ds.output) }; if (sort && sort.field) addSortField(scope, p, sort); a = scope.add(Aggregate$1(p)); v = scope.add(Collect$1({pulse: ref(a)})); v = {agg: a, ref: ref(v)}; if (k != null) cache[k] = v; } else if (sort && sort.field) { addSortField(scope, v.agg.params, sort); } return v.ref; }; function fieldKey(field$$1) { return isString(field$$1) ? field$$1 : null; } function addSortField(scope, p, sort) { var as = aggrField(sort.op, sort.field), s; if (p.ops) { for (var i=0, n=p.as.length; i<n; ++i) { if (p.as[i] === as) return; } } else { p.ops = ['count']; p.fields = [null]; p.as = ['count']; } if (sort.op) { p.ops.push((s=sort.op.signal) ? scope.signalRef(s) : sort.op); p.fields.push(scope.fieldRef(sort.field)); p.as.push(as); } } function cache(scope, ds, name, optype, field$$1, counts, index) { var cache = ds[name] || (ds[name] = {}), sort = sortKey(counts), k = fieldKey(field$$1), v, op; if (k != null) { scope = ds.scope; k = k + (sort ? '|' + sort : ''); v = cache[k]; } if (!v) { var params = counts ? {field: keyFieldRef, pulse: ds.countsRef(scope, field$$1, counts)} : {field: scope.fieldRef(field$$1), pulse: ref(ds.output)}; if (sort) params.sort = scope.sortRef(counts); op = scope.add(entry(optype, undefined, params)); if (index) ds.index[field$$1] = op; v = ref(op); if (k != null) cache[k] = v; } return v; } prototype$82.tuplesRef = function() { return ref(this.values); }; prototype$82.extentRef = function(scope, field$$1) { return cache(scope, this, 'extent', 'extent', field$$1, false); }; prototype$82.domainRef = function(scope, field$$1) { return cache(scope, this, 'domain', 'values', field$$1, false); }; prototype$82.valuesRef = function(scope, field$$1, sort) { return cache(scope, this, 'vals', 'values', field$$1, sort || true); }; prototype$82.lookupRef = function(scope, field$$1) { return cache(scope, this, 'lookup', 'tupleindex', field$$1, false); }; prototype$82.indataRef = function(scope, field$$1) { return cache(scope, this, 'indata', 'tupleindex', field$$1, true, true); }; var parseFacet = function(spec, scope, group) { var facet = spec.from.facet, name = facet.name, data = ref(scope.getData(facet.data).output), subscope, source, values, op; if (!facet.name) { error$1('Facet must have a name: ' + $$2(facet)); } if (!facet.data) { error$1('Facet must reference a data set: ' + $$2(facet)); } if (facet.field) { op = scope.add(PreFacet$1({ field: scope.fieldRef(facet.field), pulse: data })); } else if (facet.groupby) { op = scope.add(Facet$1({ key: scope.keyRef(facet.groupby), group: ref(scope.proxy(group.parent)), pulse: data })); } else { error$1('Facet must specify groupby or field: ' + $$2(facet)); } // initialize facet subscope subscope = scope.fork(); source = subscope.add(Collect$1()); values = subscope.add(Sieve$1({pulse: ref(source)})); subscope.addData(name, new DataScope(subscope, source, source, values)); subscope.addSignal('parent', null); // parse faceted subflow op.params.subflow = { $subflow: parseSpec(spec, subscope).toRuntime() }; }; var parseSubflow = function(spec, scope, input) { var op = scope.add(PreFacet$1({pulse: input.pulse})), subscope = scope.fork(); subscope.add(Sieve$1()); subscope.addSignal('parent', null); // parse group mark subflow op.params.subflow = { $subflow: parseSpec(spec, subscope).toRuntime() }; }; var parseTrigger = function(spec, scope, name) { var remove = spec.remove, insert = spec.insert, toggle = spec.toggle, modify = spec.modify, values = spec.values, op = scope.add(operator()), update, expr; update = 'if(' + spec.trigger + ',modify("' + name + '",' + [insert, remove, toggle, modify, values] .map(function(_$$1) { return _$$1 == null ? 'null' : _$$1; }) .join(',') + '),0)'; expr = parseExpression(update, scope); op.update = expr.$expr; op.params = expr.$params; }; var parseMark = function(spec, scope) { var role$$1 = role(spec), group = spec.type === GroupMark, facet = spec.from && spec.from.facet, layout = spec.layout || role$$1 === ScopeRole$1 || role$$1 === FrameRole$1, nested = role$$1 === MarkRole || layout || facet, overlap = spec.overlap, ops, op, input, store, bound, render, sieve, name, joinRef, markRef, encodeRef, layoutRef, boundRef; // resolve input data input = parseData(spec.from, group, scope); // data join to map tuples to visual items op = scope.add(DataJoin$1({ key: input.key || (spec.key ? fieldRef$1(spec.key) : undefined), pulse: input.pulse, clean: !group })); joinRef = ref(op); // collect visual items op = store = scope.add(Collect$1({pulse: joinRef})); // connect visual items to scenegraph op = scope.add(Mark$1({ markdef: definition$1(spec), context: {$context: true}, groups: scope.lookup(), parent: scope.signals.parent ? scope.signalRef('parent') : null, index: scope.markpath(), pulse: ref(op) })); markRef = ref(op); // add visual encoders op = scope.add(Encode$1( encoders(spec.encode, spec.type, role$$1, spec.style, scope, {pulse: markRef}) )); // monitor parent marks to propagate changes op.params.parent = scope.encode(); // add post-encoding transforms, if defined if (spec.transform) { spec.transform.forEach(function(_$$1) { var tx = parseTransform(_$$1, scope); if (tx.metadata.generates || tx.metadata.changes) { error$1('Mark transforms should not generate new data.'); } tx.params.pulse = ref(op); scope.add(op = tx); }); } // if item sort specified, perform post-encoding if (spec.sort) { op = scope.add(SortItems$1({ sort: scope.compareRef(spec.sort), pulse: ref(op) })); } encodeRef = ref(op); // add view layout operator if needed if (facet || layout) { layout = scope.add(ViewLayout$1({ layout: scope.objectProperty(spec.layout), legendMargin: scope.config.legendMargin, mark: markRef, pulse: encodeRef })); layoutRef = ref(layout); } // compute bounding boxes bound = scope.add(Bound$1({mark: markRef, pulse: layoutRef || encodeRef})); boundRef = ref(bound); // if group mark, recurse to parse nested content if (group) { // juggle layout & bounds to ensure they run *after* any faceting transforms if (nested) { ops = scope.operators; ops.pop(); if (layout) ops.pop(); } scope.pushState(encodeRef, layoutRef || boundRef, joinRef); facet ? parseFacet(spec, scope, input) // explicit facet : nested ? parseSubflow(spec, scope, input) // standard mark group : parseSpec(spec, scope); // guide group, we can avoid nested scopes scope.popState(); if (nested) { if (layout) ops.push(layout); ops.push(bound); } } if (overlap) { op = { method: overlap.method === true ? 'parity' : overlap.method, pulse: boundRef }; if (overlap.order) { op.sort = scope.compareRef({field: overlap.order}); } if (overlap.bound) { op.boundScale = scope.scaleRef(overlap.bound.scale); op.boundOrient = overlap.bound.orient; op.boundTolerance = overlap.bound.tolerance; } boundRef = ref(scope.add(Overlap$1(op))); } // render / sieve items render = scope.add(Render$1({pulse: boundRef})); sieve = scope.add(Sieve$1({pulse: ref(render)}, undefined, scope.parent())); // if mark is named, make accessible as reactive geometry // add trigger updates if defined if (spec.name != null) { name = spec.name; scope.addData(name, new DataScope(scope, store, render, sieve)); if (spec.on) spec.on.forEach(function(on) { if (on.insert || on.remove || on.toggle) { error$1('Marks only support modify triggers.'); } parseTrigger(on, scope, name); }); } }; var parseLegend = function(spec, scope) { var type = spec.type || 'symbol', config = scope.config.legend, encode = spec.encode || {}, legendEncode = encode.legend || {}, name = legendEncode.name || undefined, interactive = !!legendEncode.interactive, style = legendEncode.style, datum, dataRef, entryRef, group, title, entryEncode, params, children; // resolve 'canonical' scale name var scale = spec.size || spec.shape || spec.fill || spec.stroke || spec.strokeDash || spec.opacity; if (!scale) { error$1('Missing valid scale for legend.'); } // single-element data source for axis group datum = { orient: value(spec.orient, config.orient), title: spec.title != null }; dataRef = ref(scope.add(Collect$1(null, [datum]))); // encoding properties for legend group legendEncode = extendEncode({ enter: legendEnter(config), update: { offset: encoder(value(spec.offset, config.offset)), padding: encoder(value(spec.padding, config.padding)), titlePadding: encoder(value(spec.titlePadding, config.titlePadding)) } }, legendEncode, Skip); // encoding properties for legend entry sub-group entryEncode = { update: { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, entryPadding: encoder(value(spec.entryPadding, config.entryPadding)) } }; if (type === 'gradient') { // data source for gradient labels entryRef = ref(scope.add(LegendEntries$1({ type: 'gradient', scale: scope.scaleRef(scale), count: scope.objectProperty(spec.tickCount), values: scope.objectProperty(spec.values), formatSpecifier: scope.property(spec.format) }))); children = [ legendGradient(spec, scale, config, encode.gradient), legendGradientLabels(spec, config, encode.labels, entryRef) ]; } else { // data source for legend entries entryRef = ref(scope.add(LegendEntries$1(params = { scale: scope.scaleRef(scale), count: scope.objectProperty(spec.tickCount), values: scope.objectProperty(spec.values), formatSpecifier: scope.property(spec.format) }))); children = [ legendSymbols(spec, config, encode.symbols, entryRef), legendLabels(spec, config, encode.labels, entryRef) ]; params.size = sizeExpression(spec, scope, children); } // generate legend marks children = [ guideGroup(LegendEntryRole, null, null, dataRef, interactive, entryEncode, children) ]; // include legend title if defined if (datum.title) { title = legendTitle(spec, config, encode.title, dataRef); entryEncode.update.y.offset = { field: {group: 'titlePadding'}, offset: getValue$1(scope, title.encode, 'fontSize', GuideTitleStyle) }; children.push(title); } // build legend specification group = guideGroup(LegendRole$2, style, name, dataRef, interactive, legendEncode, children); if (spec.zindex) group.zindex = spec.zindex; // parse legend specification return parseMark(group, scope); }; function sizeExpression(spec, scope, marks) { var fontSize = getValue$1(scope, marks[1].encode, 'fontSize', GuideLabelStyle); if (spec.size) { return {$expr: 'Math.max(Math.ceil(Math.sqrt(_.scale(datum))),' + fontSize + ')'}; } else { var symbolSize = getValue$1(scope, marks[0].encode, 'size'); return Math.max(Math.ceil(Math.sqrt(symbolSize)), fontSize); } } function legendEnter(config) { var enter = {}, count = addEncode(enter, 'fill', config.fillColor) + addEncode(enter, 'stroke', config.strokeColor) + addEncode(enter, 'strokeWidth', config.strokeWidth) + addEncode(enter, 'strokeDash', config.strokeDash) + addEncode(enter, 'cornerRadius', config.cornerRadius); return count ? enter : undefined; } function getValue$1(scope, encode, name, style) { var v = encode && ( (encode.update && encode.update[name]) || (encode.enter && encode.enter[name]) ); return +(v ? v.value // TODO support signal? : (style && (v = scope.config.style[style]) && v[name])); } var parseTitle = function(spec, scope) { spec = isString(spec) ? {text: spec} : spec; var config = scope.config.title, encode = extend({}, spec.encode), datum, dataRef, title; // single-element data source for group title datum = { orient: spec.orient != null ? spec.orient : config.orient }; dataRef = ref(scope.add(Collect$1(null, [datum]))); // build title specification encode.name = spec.name; encode.interactive = spec.interactive; title = buildTitle(spec, config, encode, dataRef); if (spec.zindex) title.zindex = spec.zindex; // parse title specification return parseMark(title, scope); }; function buildTitle(spec, config, userEncode, dataRef) { var title = spec.text, orient = spec.orient || config.orient, anchor = spec.anchor || config.anchor, sign = (orient === Left$1 || orient === Top$1) ? -1 : 1, horizontal = (orient === Top$1 || orient === Bottom$1), extent$$1 = {group: (horizontal ? 'width' : 'height')}, encode = {}, enter, update, pos, opp, mult, align; encode.enter = enter = { opacity: {value: 0} }; addEncode(enter, 'fill', config.color); addEncode(enter, 'font', config.font); addEncode(enter, 'fontSize', config.fontSize); addEncode(enter, 'fontWeight', config.fontWeight); encode.exit = { opacity: {value: 0} }; encode.update = update = { opacity: {value: 1}, text: isObject(title) ? title : {value: title + ''}, offset: encoder((spec.offset != null ? spec.offset : config.offset) || 0) }; if (anchor === 'start') { mult = 0; align = 'left'; } else { if (anchor === 'end') { mult = 1; align = 'right'; } else { mult = 0.5; align = 'center'; } } pos = {field: extent$$1, mult: mult}; opp = sign < 0 ? {value: 0} : horizontal ? {field: {group: 'height'}} : {field: {group: 'width'}}; if (horizontal) { update.x = pos; update.y = opp; update.angle = {value: 0}; update.baseline = {value: orient === Top$1 ? 'bottom' : 'top'}; } else { update.x = opp; update.y = pos; update.angle = {value: sign * 90}; update.baseline = {value: 'bottom'}; } update.align = {value: align}; update.limit = {field: extent$$1}; addEncode(update, 'angle', config.angle); addEncode(update, 'baseline', config.baseline); addEncode(update, 'limit', config.limit); return guideMark(TextMark, TitleRole$1, spec.style || GroupTitleStyle, null, dataRef, encode, userEncode); } function parseData$1(data, scope) { var transforms = []; if (data.transform) { data.transform.forEach(function(tx) { transforms.push(parseTransform(tx, scope)); }); } if (data.on) { data.on.forEach(function(on) { parseTrigger(on, scope, data.name); }); } scope.addDataPipeline(data.name, analyze(data, scope, transforms)); } /** * Analyze a data pipeline, add needed operators. */ function analyze(data, scope, ops) { // POSSIBLE TODOs: // - error checking for treesource on tree operators (BUT what if tree is upstream?) // - this is local analysis, perhaps some tasks better for global analysis... var output = [], source = null, modify = false, generate = false, upstream, i, n, t, m; if (data.values) { // hard-wired input data set output.push(source = collect({$ingest: data.values, $format: data.format})); } else if (data.url) { // load data from external source output.push(source = collect({$request: data.url, $format: data.format})); } else if (data.source) { // derives from one or more other data sets source = upstream = array(data.source).map(function(d) { return ref(scope.getData(d).output); }); output.push(null); // populate later } // scan data transforms, add collectors as needed for (i=0, n=ops.length; i<n; ++i) { t = ops[i]; m = t.metadata; if (!source && !m.source) { output.push(source = collect()); } output.push(t); if (m.generates) generate = true; if (m.modifies && !generate) modify = true; if (m.source) source = t; else if (m.changes) source = null; } if (upstream) { n = upstream.length - 1; output[0] = Relay$1({ derive: modify, pulse: n ? upstream : upstream[0] }); if (modify || n) { // collect derived and multi-pulse tuples output.splice(1, 0, collect()); } } if (!source) output.push(collect()); output.push(Sieve$1({})); return output; } function collect(values) { var s = Collect$1({}, values); s.metadata = {source: true}; return s; } var axisConfig = function(spec, scope) { var config = scope.config, orient = spec.orient, xy = (orient === Top$1 || orient === Bottom$1) ? config.axisX : config.axisY, or = config['axis' + orient[0].toUpperCase() + orient.slice(1)], band = scope.scaleType(spec.scale) === 'band' && config.axisBand; return (xy || or || band) ? extend({}, config.axis, xy, or, band) : config.axis; }; var axisDomain = function(spec, config, userEncode, dataRef) { var orient = spec.orient, zero = {value: 0}, encode = {}, enter, update, u, u2, v; encode.enter = enter = { opacity: zero }; addEncode(enter, 'stroke', config.domainColor); addEncode(enter, 'strokeWidth', config.domainWidth); encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; if (orient === Top$1 || orient === Bottom$1) { u = 'x'; v = 'y'; } else { u = 'y'; v = 'x'; } u2 = u + '2'; enter[v] = zero; update[u] = enter[u] = position(spec, 0); update[u2] = enter[u2] = position(spec, 1); return guideMark(RuleMark, AxisDomainRole, null, null, dataRef, encode, userEncode); }; function position(spec, pos) { return {scale: spec.scale, range: pos}; } var axisGrid = function(spec, config, userEncode, dataRef) { var orient = spec.orient, vscale = spec.gridScale, sign = (orient === Left$1 || orient === Top$1) ? 1 : -1, offset = sign * spec.offset || 0, zero = {value: 0}, encode = {}, enter, exit, update, tickPos, u, v, v2, s; encode.enter = enter = { opacity: zero }; addEncode(enter, 'stroke', config.gridColor); addEncode(enter, 'strokeWidth', config.gridWidth); addEncode(enter, 'strokeDash', config.gridDash); encode.exit = exit = { opacity: zero }; encode.update = update = {}; addEncode(update, 'opacity', config.gridOpacity); tickPos = { scale: spec.scale, field: Value, band: config.bandPosition, round: config.tickRound, extra: config.tickExtra, offset: config.tickOffset }; if (orient === Top$1 || orient === Bottom$1) { u = 'x'; v = 'y'; s = 'height'; } else { u = 'y'; v = 'x'; s = 'width'; } v2 = v + '2'; update[u] = enter[u] = exit[u] = tickPos; if (vscale) { enter[v] = {scale: vscale, range: 0, mult: sign, offset: offset}; update[v2] = enter[v2] = {scale: vscale, range: 1, mult: sign, offset: offset}; } else { enter[v] = {value: offset}; update[v2] = enter[v2] = {signal: s, mult: sign, offset: offset}; } return guideMark(RuleMark, AxisGridRole, null, Value, dataRef, encode, userEncode); }; var axisTicks = function(spec, config, userEncode, dataRef, size) { var orient = spec.orient, sign = (orient === Left$1 || orient === Top$1) ? -1 : 1, zero = {value: 0}, encode = {}, enter, exit, update, tickSize, tickPos; encode.enter = enter = { opacity: zero }; addEncode(enter, 'stroke', config.tickColor); addEncode(enter, 'strokeWidth', config.tickWidth); encode.exit = exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; tickSize = encoder(size); tickSize.mult = sign; tickPos = { scale: spec.scale, field: Value, band: config.bandPosition, round: config.tickRound, extra: config.tickExtra, offset: config.tickOffset }; if (orient === Top$1 || orient === Bottom$1) { update.y = enter.y = zero; update.y2 = enter.y2 = tickSize; update.x = enter.x = exit.x = tickPos; } else { update.x = enter.x = zero; update.x2 = enter.x2 = tickSize; update.y = enter.y = exit.y = tickPos; } return guideMark(RuleMark, AxisTickRole, null, Value, dataRef, encode, userEncode); }; function flushExpr(scale, threshold, a, b, c) { return { signal: 'flush(range("' + scale + '"), ' + 'scale("' + scale + '", datum.value), ' + threshold + ',' + a + ',' + b + ',' + c + ')' }; } var axisLabels = function(spec, config, userEncode, dataRef, size) { var orient = spec.orient, sign = (orient === Left$1 || orient === Top$1) ? -1 : 1, scale = spec.scale, pad = value(spec.labelPadding, config.labelPadding), bound = value(spec.labelBound, config.labelBound), flush = value(spec.labelFlush, config.labelFlush), flushOn = flush != null && flush !== false && (flush = +flush) === flush, flushOffset = +value(spec.labelFlushOffset, config.labelFlushOffset), overlap = value(spec.labelOverlap, config.labelOverlap), zero = {value: 0}, encode = {}, enter, exit, update, tickSize, tickPos; encode.enter = enter = { opacity: zero }; addEncode(enter, 'angle', config.labelAngle); addEncode(enter, 'fill', config.labelColor); addEncode(enter, 'font', config.labelFont); addEncode(enter, 'fontSize', config.labelFontSize); addEncode(enter, 'fontWeight', config.labelFontWeight); addEncode(enter, 'limit', config.labelLimit); encode.exit = exit = { opacity: zero }; encode.update = update = { opacity: {value: 1}, text: {field: Label} }; tickSize = encoder(size); tickSize.mult = sign; tickSize.offset = encoder(pad); tickSize.offset.mult = sign; tickPos = { scale: scale, field: Value, band: 0.5, offset: config.tickOffset }; if (orient === Top$1 || orient === Bottom$1) { update.y = enter.y = tickSize; update.x = enter.x = exit.x = tickPos; addEncode(update, 'align', flushOn ? flushExpr(scale, flush, '"left"', '"right"', '"center"') : 'center'); if (flushOn && flushOffset) { addEncode(update, 'dx', flushExpr(scale, flush, -flushOffset, flushOffset, 0)); } addEncode(update, 'baseline', orient === Top$1 ? 'bottom' : 'top'); } else { update.x = enter.x = tickSize; update.y = enter.y = exit.y = tickPos; addEncode(update, 'align', orient === Right$1 ? 'left' : 'right'); addEncode(update, 'baseline', flushOn ? flushExpr(scale, flush, '"bottom"', '"top"', '"middle"') : 'middle'); if (flushOn && flushOffset) { addEncode(update, 'dy', flushExpr(scale, flush, flushOffset, -flushOffset, 0)); } } spec = guideMark(TextMark, AxisLabelRole, GuideLabelStyle, Value, dataRef, encode, userEncode); if (overlap || bound) { spec.overlap = { method: overlap, order: 'datum.index', bound: bound ? {scale: scale, orient: orient, tolerance: +bound} : null }; } return spec; }; var axisTitle = function(spec, config, userEncode, dataRef) { var orient = spec.orient, title = spec.title, sign = (orient === Left$1 || orient === Top$1) ? -1 : 1, horizontal = (orient === Top$1 || orient === Bottom$1), encode = {}, enter, update, titlePos; encode.enter = enter = { opacity: {value: 0} }; addEncode(enter, 'align', config.titleAlign); addEncode(enter, 'fill', config.titleColor); addEncode(enter, 'font', config.titleFont); addEncode(enter, 'fontSize', config.titleFontSize); addEncode(enter, 'fontWeight', config.titleFontWeight); addEncode(enter, 'limit', config.titleLimit); encode.exit = { opacity: {value: 0} }; encode.update = update = { opacity: {value: 1}, text: title && title.signal ? {signal: title.signal} : {value: title + ''} }; titlePos = { scale: spec.scale, range: 0.5 }; if (horizontal) { update.x = titlePos; update.angle = {value: 0}; update.baseline = {value: orient === Top$1 ? 'bottom' : 'top'}; } else { update.y = titlePos; update.angle = {value: sign * 90}; update.baseline = {value: 'bottom'}; } addEncode(update, 'angle', config.titleAngle); addEncode(update, 'baseline', config.titleBaseline); !addEncode(update, 'x', config.titleX) && horizontal && !has('x', userEncode) && (encode.enter.auto = {value: true}); !addEncode(update, 'y', config.titleY) && !horizontal && !has('y', userEncode) && (encode.enter.auto = {value: true}); return guideMark(TextMark, AxisTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode); }; var parseAxis = function(spec, scope) { var config = axisConfig(spec, scope), encode = spec.encode || {}, axisEncode = encode.axis || {}, name = axisEncode.name || undefined, interactive = !!axisEncode.interactive, style = axisEncode.style, datum, dataRef, ticksRef, size, group, children; // single-element data source for axis group datum = { orient: spec.orient, ticks: !!value(spec.ticks, config.ticks), labels: !!value(spec.labels, config.labels), grid: !!value(spec.grid, config.grid), domain: !!value(spec.domain, config.domain), title: !!value(spec.title, false) }; dataRef = ref(scope.add(Collect$1({}, [datum]))); // encoding properties for axis group item axisEncode = extendEncode({ update: { range: {signal: 'abs(span(range("' + spec.scale + '")))'}, offset: encoder(value(spec.offset, 0)), position: encoder(value(spec.position, 0)), titlePadding: encoder(value(spec.titlePadding, config.titlePadding)), minExtent: encoder(value(spec.minExtent, config.minExtent)), maxExtent: encoder(value(spec.maxExtent, config.maxExtent)) } }, encode.axis, Skip); // data source for axis ticks ticksRef = ref(scope.add(AxisTicks$1({ scale: scope.scaleRef(spec.scale), extra: config.tickExtra, count: scope.objectProperty(spec.tickCount), values: scope.objectProperty(spec.values), formatSpecifier: scope.property(spec.format) }))); // generate axis marks children = []; // include axis gridlines if requested if (datum.grid) { children.push(axisGrid(spec, config, encode.grid, ticksRef)); } // include axis ticks if requested if (datum.ticks) { size = value(spec.tickSize, config.tickSize); children.push(axisTicks(spec, config, encode.ticks, ticksRef, size)); } // include axis labels if requested if (datum.labels) { size = datum.ticks ? size : 0; children.push(axisLabels(spec, config, encode.labels, ticksRef, size)); } // include axis domain path if requested if (datum.domain) { children.push(axisDomain(spec, config, encode.domain, dataRef)); } // include axis title if defined if (datum.title) { children.push(axisTitle(spec, config, encode.title, dataRef)); } // build axis specification group = guideGroup(AxisRole$2, style, name, dataRef, interactive, axisEncode, children); if (spec.zindex) group.zindex = spec.zindex; // parse axis specification return parseMark(group, scope); }; var parseSpec = function(spec, scope, preprocessed) { var signals = array(spec.signals), scales = array(spec.scales); if (!preprocessed) signals.forEach(function(_$$1) { parseSignal(_$$1, scope); }); array(spec.projections).forEach(function(_$$1) { parseProjection(_$$1, scope); }); scales.forEach(function(_$$1) { initScale(_$$1, scope); }); array(spec.data).forEach(function(_$$1) { parseData$1(_$$1, scope); }); scales.forEach(function(_$$1) { parseScale(_$$1, scope); }); signals.forEach(function(_$$1) { parseSignalUpdates(_$$1, scope); }); array(spec.axes).forEach(function(_$$1) { parseAxis(_$$1, scope); }); array(spec.marks).forEach(function(_$$1) { parseMark(_$$1, scope); }); array(spec.legends).forEach(function(_$$1) { parseLegend(_$$1, scope); }); if (spec.title) { parseTitle(spec.title, scope); } scope.parseLambdas(); return scope; }; var defined = toSet(['width', 'height', 'padding', 'autosize']); function parseView(spec, scope) { var config = scope.config, op, input, encode, parent, root; scope.background = spec.background || config.background; scope.eventConfig = config.events; root = ref(scope.root = scope.add(operator())); scope.addSignal('width', spec.width || 0); scope.addSignal('height', spec.height || 0); scope.addSignal('padding', parsePadding(spec.padding, config)); scope.addSignal('autosize', parseAutosize(spec.autosize, config)); array(spec.signals).forEach(function(_$$1) { if (!defined[_$$1.name]) parseSignal(_$$1, scope); }); // Store root group item input = scope.add(Collect$1()); // Encode root group item encode = extendEncode({ enter: { x: {value: 0}, y: {value: 0} }, update: { width: {signal: 'width'}, height: {signal: 'height'} } }, spec.encode); encode = scope.add(Encode$1( encoders(encode, GroupMark, FrameRole$1, spec.style, scope, {pulse: ref(input)})) ); // Perform view layout parent = scope.add(ViewLayout$1({ layout: scope.objectProperty(spec.layout), legendMargin: config.legendMargin, autosize: scope.signalRef('autosize'), mark: root, pulse: ref(encode) })); scope.operators.pop(); // Parse remainder of specification scope.pushState(ref(encode), ref(parent), null); parseSpec(spec, scope, true); scope.operators.push(parent); // Bound / render / sieve root item op = scope.add(Bound$1({mark: root, pulse: ref(parent)})); op = scope.add(Render$1({pulse: ref(op)})); op = scope.add(Sieve$1({pulse: ref(op)})); // Track metadata for root item scope.addData('root', new DataScope(scope, input, input, op)); return scope; } function Scope(config) { this.config = config; this.bindings = []; this.field = {}; this.signals = {}; this.lambdas = {}; this.scales = {}; this.events = {}; this.data = {}; this.streams = []; this.updates = []; this.operators = []; this.background = null; this.eventConfig = null; this._id = 0; this._subid = 0; this._nextsub = [0]; this._parent = []; this._encode = []; this._lookup = []; this._markpath = []; } function Subscope(scope) { this.config = scope.config; this.field = Object.create(scope.field); this.signals = Object.create(scope.signals); this.lambdas = Object.create(scope.lambdas); this.scales = Object.create(scope.scales); this.events = Object.create(scope.events); this.data = Object.create(scope.data); this.streams = []; this.updates = []; this.operators = []; this._id = 0; this._subid = ++scope._nextsub[0]; this._nextsub = scope._nextsub; this._parent = scope._parent.slice(); this._encode = scope._encode.slice(); this._lookup = scope._lookup.slice(); this._markpath = scope._markpath; } var prototype$83 = Scope.prototype = Subscope.prototype; // ---- prototype$83.fork = function() { return new Subscope(this); }; prototype$83.toRuntime = function() { this.finish(); return { background: this.background, operators: this.operators, streams: this.streams, updates: this.updates, bindings: this.bindings, eventConfig: this.eventConfig }; }; prototype$83.id = function() { return (this._subid ? this._subid + ':' : 0) + this._id++; }; prototype$83.add = function(op) { this.operators.push(op); op.id = this.id(); // if pre-registration references exist, resolve them now if (op.refs) { op.refs.forEach(function(ref$$1) { ref$$1.$ref = op.id; }); op.refs = null; } return op; }; prototype$83.proxy = function(op) { var vref = op instanceof Entry ? ref(op) : op; return this.add(Proxy$1({value: vref})); }; prototype$83.addStream = function(stream) { this.streams.push(stream); stream.id = this.id(); return stream; }; prototype$83.addUpdate = function(update) { this.updates.push(update); return update; }; // Apply metadata prototype$83.finish = function() { var name, ds; // annotate root if (this.root) this.root.root = true; // annotate signals for (name in this.signals) { this.signals[name].signal = name; } // annotate scales for (name in this.scales) { this.scales[name].scale = name; } // annotate data sets function annotate(op, name, type) { var data, list; if (op) { data = op.data || (op.data = {}); list = data[name] || (data[name] = []); list.push(type); } } for (name in this.data) { ds = this.data[name]; annotate(ds.input, name, 'input'); annotate(ds.output, name, 'output'); annotate(ds.values, name, 'values'); for (var field$$1 in ds.index) { annotate(ds.index[field$$1], name, 'index:' + field$$1); } } return this; }; // ---- prototype$83.pushState = function(encode, parent, lookup) { this._encode.push(ref(this.add(Sieve$1({pulse: encode})))); this._parent.push(parent); this._lookup.push(lookup ? ref(this.proxy(lookup)) : null); this._markpath.push(-1); }; prototype$83.popState = function() { this._encode.pop(); this._parent.pop(); this._lookup.pop(); this._markpath.pop(); }; prototype$83.parent = function() { return peek(this._parent); }; prototype$83.encode = function() { return peek(this._encode); }; prototype$83.lookup = function() { return peek(this._lookup); }; prototype$83.markpath = function() { var p = this._markpath; return ++p[p.length-1]; }; // ---- prototype$83.fieldRef = function(field$$1, name) { if (isString(field$$1)) return fieldRef$1(field$$1, name); if (!field$$1.signal) { error$1('Unsupported field reference: ' + $$2(field$$1)); } var s = field$$1.signal, f = this.field[s], params; if (!f) { // TODO: replace with update signalRef? params = {name: this.signalRef(s)}; if (name) params.as = name; this.field[s] = f = ref(this.add(Field$1(params))); } return f; }; prototype$83.compareRef = function(cmp) { function check(_$$1) { if (isSignal(_$$1)) { signal = true; return ref(sig[_$$1.signal]); } else { return _$$1; } } var sig = this.signals, signal = false, fields = array(cmp.field).map(check), orders = array(cmp.order).map(check); return signal ? ref(this.add(Compare$1({fields: fields, orders: orders}))) : compareRef(fields, orders); }; prototype$83.keyRef = function(fields, flat) { function check(_$$1) { if (isSignal(_$$1)) { signal = true; return ref(sig[_$$1.signal]); } else { return _$$1; } } var sig = this.signals, signal = false; fields = array(fields).map(check); return signal ? ref(this.add(Key$1({fields: fields, flat: flat}))) : keyRef(fields, flat); }; prototype$83.sortRef = function(sort) { if (!sort) return sort; // including id ensures stable sorting var a = [aggrField(sort.op, sort.field), tupleidRef], o = sort.order || Ascending; return o.signal ? ref(this.add(Compare$1({ fields: a, orders: [o = this.signalRef(o.signal), o] }))) : compareRef(a, [o, o]); }; // ---- prototype$83.event = function(source, type) { var key$$1 = source + ':' + type; if (!this.events[key$$1]) { var id$$1 = this.id(); this.streams.push({ id: id$$1, source: source, type: type }); this.events[key$$1] = id$$1; } return this.events[key$$1]; }; // ---- prototype$83.addSignal = function(name, value$$1) { if (this.signals.hasOwnProperty(name)) { error$1('Duplicate signal name: ' + $$2(name)); } var op = value$$1 instanceof Entry ? value$$1 : this.add(operator(value$$1)); return this.signals[name] = op; }; prototype$83.getSignal = function(name) { if (!this.signals[name]) { error$1('Unrecognized signal name: ' + $$2(name)); } return this.signals[name]; }; prototype$83.signalRef = function(s) { if (this.signals[s]) { return ref(this.signals[s]); } else if (!this.lambdas.hasOwnProperty(s)) { this.lambdas[s] = this.add(operator(null)); } return ref(this.lambdas[s]); }; prototype$83.parseLambdas = function() { var code = Object.keys(this.lambdas); for (var i=0, n=code.length; i<n; ++i) { var s = code[i], e = parseExpression(s, this), op = this.lambdas[s]; op.params = e.$params; op.update = e.$expr; } }; prototype$83.property = function(spec) { return spec && spec.signal ? this.signalRef(spec.signal) : spec; }; prototype$83.objectProperty = function(spec) { return (!spec || !isObject(spec)) ? spec : this.signalRef(spec.signal || propertyLambda(spec)); }; function propertyLambda(spec) { return (isArray(spec) ? arrayLambda : objectLambda)(spec); } function arrayLambda(array$$1) { var code = '[', i = 0, n = array$$1.length, value$$1; for (; i<n; ++i) { value$$1 = array$$1[i]; code += (i > 0 ? ',' : '') + (isObject(value$$1) ? (value$$1.signal || propertyLambda(value$$1)) : $$2(value$$1)); } return code + ']'; } function objectLambda(obj) { var code = '{', i = 0, key$$1, value$$1; for (key$$1 in obj) { value$$1 = obj[key$$1]; code += (++i > 1 ? ',' : '') + $$2(key$$1) + ':' + (isObject(value$$1) ? (value$$1.signal || propertyLambda(value$$1)) : $$2(value$$1)); } return code + '}'; } prototype$83.addBinding = function(name, bind) { if (!this.bindings) { error$1('Nested signals do not support binding: ' + $$2(name)); } this.bindings.push(extend({signal: name}, bind)); }; // ---- prototype$83.addScaleProj = function(name, transform) { if (this.scales.hasOwnProperty(name)) { error$1('Duplicate scale or projection name: ' + $$2(name)); } this.scales[name] = this.add(transform); }; prototype$83.addScale = function(name, params) { this.addScaleProj(name, Scale$1(params)); }; prototype$83.addProjection = function(name, params) { this.addScaleProj(name, Projection$1(params)); }; prototype$83.getScale = function(name) { if (!this.scales[name]) { error$1('Unrecognized scale name: ' + $$2(name)); } return this.scales[name]; }; prototype$83.projectionRef = prototype$83.scaleRef = function(name) { return ref(this.getScale(name)); }; prototype$83.projectionType = prototype$83.scaleType = function(name) { return this.getScale(name).params.type; }; // ---- prototype$83.addData = function(name, dataScope) { if (this.data.hasOwnProperty(name)) { error$1('Duplicate data set name: ' + $$2(name)); } return (this.data[name] = dataScope); }; prototype$83.getData = function(name) { if (!this.data[name]) { error$1('Undefined data set name: ' + $$2(name)); } return this.data[name]; }; prototype$83.addDataPipeline = function(name, entries) { if (this.data.hasOwnProperty(name)) { error$1('Duplicate data set name: ' + $$2(name)); } return this.addData(name, DataScope.fromEntries(this, entries)); }; var defaults = function(configs) { var output = defaults$1(); (configs || []).forEach(function(config) { var key$$1, value, style; if (config) { for (key$$1 in config) { if (key$$1 === 'style') { style = output.style || (output.style = {}); for (key$$1 in config.style) { style[key$$1] = extend(style[key$$1] || {}, config.style[key$$1]); } } else { value = config[key$$1]; output[key$$1] = isObject(value) && !isArray(value) ? extend(isObject(output[key$$1]) ? output[key$$1] : {}, value) : value; } } } }); return output; }; var defaultFont = 'sans-serif'; var defaultSymbolSize = 30; var defaultStrokeWidth = 2; var defaultColor = '#4c78a8'; var black = "#000"; var gray = '#888'; var lightGray = '#ddd'; /** * Standard configuration defaults for Vega specification parsing. * Users can provide their own (sub-)set of these default values * by passing in a config object to the top-level parse method. */ function defaults$1() { return { // default padding around visualization padding: 0, // default for automatic sizing; options: "none", "pad", "fit" // or provide an object (e.g., {"type": "pad", "resize": true}) autosize: 'pad', // default view background color // covers the entire view component background: null, // default event handling configuration // preventDefault for view-sourced event types except 'wheel' events: { defaults: {allow: ['wheel']} }, // defaults for top-level group marks // accepts mark properties (fill, stroke, etc) // covers the data rectangle within group width/height group: null, // defaults for basic mark types // each subset accepts mark properties (fill, stroke, etc) mark: null, arc: { fill: defaultColor }, area: { fill: defaultColor }, image: null, line: { stroke: defaultColor, strokeWidth: defaultStrokeWidth }, path: { stroke: defaultColor }, rect: { fill: defaultColor }, rule: { stroke: black }, shape: { stroke: defaultColor }, symbol: { fill: defaultColor, size: 64 }, text: { fill: black, font: defaultFont, fontSize: 11 }, // style definitions style: { // axis & legend labels "guide-label": { fill: black, font: defaultFont, fontSize: 10 }, // axis & legend titles "guide-title": { fill: black, font: defaultFont, fontSize: 11, fontWeight: 'bold' }, // headers, including chart title "group-title": { fill: black, font: defaultFont, fontSize: 13, fontWeight: 'bold' }, // defaults for styled point marks in Vega-Lite point: { size: defaultSymbolSize, strokeWidth: defaultStrokeWidth, shape: 'circle' }, circle: { size: defaultSymbolSize, strokeWidth: defaultStrokeWidth }, square: { size: defaultSymbolSize, strokeWidth: defaultStrokeWidth, shape: 'square' }, // defaults for styled group marks in Vega-Lite cell: { fill: 'transparent', stroke: lightGray } }, // defaults for axes axis: { minExtent: 0, maxExtent: 200, bandPosition: 0.5, domain: true, domainWidth: 1, domainColor: gray, grid: false, gridWidth: 1, gridColor: lightGray, gridOpacity: 1, labels: true, labelAngle: 0, labelLimit: 180, labelPadding: 2, ticks: true, tickColor: gray, tickOffset: 0, tickRound: true, tickSize: 5, tickWidth: 1, titleAlign: 'center', titlePadding: 4 }, // correction for centering bias axisBand: { tickOffset: -1 }, // defaults for legends legend: { orient: 'right', offset: 18, padding: 0, entryPadding: 5, titlePadding: 5, gradientWidth: 100, gradientHeight: 20, gradientStrokeColor: lightGray, gradientStrokeWidth: 0, gradientLabelBaseline: 'top', gradientLabelOffset: 2, labelAlign: 'left', labelBaseline: 'middle', labelOffset: 8, labelLimit: 160, symbolType: 'circle', symbolSize: 100, symbolFillColor: 'transparent', symbolStrokeColor: gray, symbolStrokeWidth: 1.5, titleAlign: 'left', titleBaseline: 'top', titleLimit: 180 }, // defaults for group title title: { orient: 'top', anchor: 'middle', offset: 4 }, // defaults for scale ranges range: { category: { scheme: 'tableau10' }, ordinal: { scheme: 'blues', extent: [0.2, 1] }, heatmap: { scheme: 'viridis' }, ramp: { scheme: 'blues', extent: [0.2, 1] }, diverging: { scheme: 'blueorange' }, symbol: [ 'circle', 'square', 'triangle-up', 'cross', 'diamond', 'triangle-right', 'triangle-down', 'triangle-left' ] } }; } var parse$2 = function(spec, config) { if (!isObject(spec)) error$1('Input Vega specification must be an object.'); return parseView(spec, new Scope(defaults([config, spec.config]))) .toRuntime(); }; /** * Parse an expression given the argument signature and body code. */ function expression$1(args, code, ctx) { // wrap code in return statement if expression does not terminate if (code[code.length-1] !== ';') { code = 'return(' + code + ');'; } var fn = Function.apply(null, args.concat(code)); return ctx && ctx.functions ? fn.bind(ctx.functions) : fn; } /** * Parse an expression used to update an operator value. */ function operatorExpression(code, ctx) { return expression$1(['_'], code, ctx); } /** * Parse an expression provided as an operator parameter value. */ function parameterExpression(code, ctx) { return expression$1(['datum', '_'], code, ctx); } /** * Parse an expression applied to an event stream. */ function eventExpression(code, ctx) { return expression$1(['event'], code, ctx); } /** * Parse an expression used to handle an event-driven operator update. */ function handlerExpression(code, ctx) { return expression$1(['_', 'event'], code, ctx); } /** * Parse an expression that performs visual encoding. */ function encodeExpression(code, ctx) { return expression$1(['item', '_'], code, ctx); } /** * Parse a set of operator parameters. */ function parseParameters$1(spec, ctx, params) { params = params || {}; var key$$1, value; for (key$$1 in spec) { value = spec[key$$1]; if (value && value.$expr && value.$params) { // if expression, parse its parameters parseParameters$1(value.$params, ctx, params); } params[key$$1] = isArray(value) ? value.map(function(v) { return parseParameter$2(v, ctx); }) : parseParameter$2(value, ctx); } return params; } /** * Parse a single parameter. */ function parseParameter$2(spec, ctx) { if (!spec || !isObject(spec)) return spec; for (var i=0, n=PARSERS.length, p; i<n; ++i) { p = PARSERS[i]; if (spec.hasOwnProperty(p.key)) { return p.parse(spec, ctx); } } return spec; } /** Reference parsers. */ var PARSERS = [ {key: '$ref', parse: getOperator}, {key: '$key', parse: getKey}, {key: '$expr', parse: getExpression}, {key: '$field', parse: getField$1}, {key: '$encode', parse: getEncode}, {key: '$compare', parse: getCompare}, {key: '$context', parse: getContext}, {key: '$subflow', parse: getSubflow}, {key: '$tupleid', parse: getTupleId} ]; /** * Resolve an operator reference. */ function getOperator(_$$1, ctx) { return ctx.get(_$$1.$ref) || error$1('Operator not defined: ' + _$$1.$ref); } /** * Resolve an expression reference. */ function getExpression(_$$1, ctx) { var k = 'e:' + _$$1.$expr; return ctx.fn[k] || (ctx.fn[k] = accessor(parameterExpression(_$$1.$expr, ctx), _$$1.$fields, _$$1.$name)); } /** * Resolve a key accessor reference. */ function getKey(_$$1, ctx) { var k = 'k:' + _$$1.$key + '_' + (!!_$$1.$flat); return ctx.fn[k] || (ctx.fn[k] = key(_$$1.$key, _$$1.$flat)); } /** * Resolve a field accessor reference. */ function getField$1(_$$1, ctx) { if (!_$$1.$field) return null; var k = 'f:' + _$$1.$field + '_' + _$$1.$name; return ctx.fn[k] || (ctx.fn[k] = field(_$$1.$field, _$$1.$name)); } /** * Resolve a comparator function reference. */ function getCompare(_$$1, ctx) { var k = 'c:' + _$$1.$compare + '_' + _$$1.$order, c = array(_$$1.$compare).map(function(_$$1) { return (_$$1 && _$$1.$tupleid) ? tupleid : _$$1; }); return ctx.fn[k] || (ctx.fn[k] = compare(c, _$$1.$order)); } /** * Resolve an encode operator reference. */ function getEncode(_$$1, ctx) { var spec = _$$1.$encode, encode = {}, name, enc; for (name in spec) { enc = spec[name]; encode[name] = accessor(encodeExpression(enc.$expr, ctx), enc.$fields); encode[name].output = enc.$output; } return encode; } /** * Resolve an context reference. */ function getContext(_$$1, ctx) { return ctx; } /** * Resolve a recursive subflow specification. */ function getSubflow(_$$1, ctx) { var spec = _$$1.$subflow; return function(dataflow, key$$1, parent) { var subctx = parseDataflow(spec, ctx.fork()), op = subctx.get(spec.operators[0].id), p = subctx.signals.parent; if (p) p.set(parent); return op; }; } /** * Resolve a tuple id reference. */ function getTupleId() { return tupleid; } function canonicalType(type) { return (type + '').toLowerCase(); } function isOperator(type) { return canonicalType(type) === 'operator'; } function isCollect(type) { return canonicalType(type) === 'collect'; } /** * Parse a dataflow operator. */ var parseOperator = function(spec, ctx) { if (isOperator(spec.type) || !spec.type) { ctx.operator(spec, spec.update ? operatorExpression(spec.update, ctx) : null); } else { ctx.transform(spec, spec.type); } }; /** * Parse and assign operator parameters. */ function parseOperatorParameters(spec, ctx) { var op, params; if (spec.params) { if (!(op = ctx.get(spec.id))) { error$1('Invalid operator id: ' + spec.id); } params = parseParameters$1(spec.params, ctx); ctx.dataflow.connect(op, op.parameters(params)); } } /** * Parse an event stream specification. */ var parseStream$3 = function(spec, ctx) { var filter = spec.filter != null ? eventExpression(spec.filter, ctx) : undefined, stream = spec.stream != null ? ctx.get(spec.stream) : undefined, args; if (spec.source) { stream = ctx.events(spec.source, spec.type, filter); } else if (spec.merge) { args = spec.merge.map(ctx.get.bind(ctx)); stream = args[0].merge.apply(args[0], args.slice(1)); } if (spec.between) { args = spec.between.map(ctx.get.bind(ctx)); stream = stream.between(args[0], args[1]); } if (spec.filter) { stream = stream.filter(filter); } if (spec.throttle != null) { stream = stream.throttle(+spec.throttle); } if (spec.debounce != null) { stream = stream.debounce(+spec.debounce); } if (stream == null) { error$1('Invalid stream definition: ' + JSON.stringify(spec)); } if (spec.consume) stream.consume(true); ctx.stream(spec, stream); }; /** * Parse an event-driven operator update. */ var parseUpdate$1 = function(spec, ctx) { var source = ctx.get(spec.source), target = null, update = spec.update, params = undefined; if (!source) error$1('Source not defined: ' + spec.source); if (spec.target && spec.target.$expr) { target = eventExpression(spec.target.$expr, ctx); } else { target = ctx.get(spec.target); } if (update && update.$expr) { if (update.$params) { params = parseParameters$1(update.$params, ctx); } update = handlerExpression(update.$expr, ctx); } ctx.update(spec, source, target, update, params); }; /** * Parse a serialized dataflow specification. */ var parseDataflow = function(spec, ctx) { var operators = spec.operators || []; // parse background if (spec.background) { ctx.background = spec.background; } // parse event configuration if (spec.eventConfig) { ctx.eventConfig = spec.eventConfig; } // parse operators operators.forEach(function(entry) { parseOperator(entry, ctx); }); // parse operator parameters operators.forEach(function(entry) { parseOperatorParameters(entry, ctx); }); // parse streams (spec.streams || []).forEach(function(entry) { parseStream$3(entry, ctx); }); // parse updates (spec.updates || []).forEach(function(entry) { parseUpdate$1(entry, ctx); }); return ctx.resolve(); }; var SKIP$3 = {skip: true}; function getState(options) { var ctx = this, state = {}; if (options.signals) { var signals = (state.signals = {}); Object.keys(ctx.signals).forEach(function(key$$1) { var op = ctx.signals[key$$1]; if (options.signals(key$$1, op)) { signals[key$$1] = op.value; } }); } if (options.data) { var data = (state.data = {}); Object.keys(ctx.data).forEach(function(key$$1) { var dataset = ctx.data[key$$1]; if (options.data(key$$1, dataset)) { data[key$$1] = dataset.input.value; } }); } if (ctx.subcontext && options.recurse !== false) { state.subcontext = ctx.subcontext.map(function(ctx) { return ctx.getState(options); }); } return state; } function setState(state) { var ctx = this, df = ctx.dataflow, data = state.data, signals = state.signals; Object.keys(signals || {}).forEach(function(key$$1) { df.update(ctx.signals[key$$1], signals[key$$1], SKIP$3); }); Object.keys(data || {}).forEach(function(key$$1) { df.pulse( ctx.data[key$$1].input, df.changeset().remove(truthy).insert(data[key$$1]) ); }); (state.subcontext || []).forEach(function(substate, i) { var subctx = ctx.subcontext[i]; if (subctx) subctx.setState(substate); }); } /** * Context objects store the current parse state. * Enables lookup of parsed operators, event streams, accessors, etc. * Provides a 'fork' method for creating child contexts for subflows. */ var context$2 = function(df, transforms, functions) { return new Context(df, transforms, functions); }; function Context(df, transforms, functions) { this.dataflow = df; this.transforms = transforms; this.events = df.events.bind(df); this.signals = {}; this.scales = {}; this.nodes = {}; this.data = {}; this.fn = {}; if (functions) { this.functions = Object.create(functions); this.functions.context = this; } } function ContextFork(ctx) { this.dataflow = ctx.dataflow; this.transforms = ctx.transforms; this.functions = ctx.functions; this.events = ctx.events; this.signals = Object.create(ctx.signals); this.scales = Object.create(ctx.scales); this.nodes = Object.create(ctx.nodes); this.data = Object.create(ctx.data); this.fn = Object.create(ctx.fn); if (ctx.functions) { this.functions = Object.create(ctx.functions); this.functions.context = this; } } Context.prototype = ContextFork.prototype = { fork: function() { var ctx = new ContextFork(this); (this.subcontext || (this.subcontext = [])).push(ctx); return ctx; }, get: function(id) { return this.nodes[id]; }, set: function(id, node) { return this.nodes[id] = node; }, add: function(spec, op) { var ctx = this, df = ctx.dataflow, data; ctx.set(spec.id, op); if (isCollect(spec.type) && (data = spec.value)) { if (data.$ingest) { df.ingest(op, data.$ingest, data.$format); } else if (data.$request) { df.request(op, data.$request, data.$format); } else { df.pulse(op, df.changeset().insert(data)); } } if (spec.root) { ctx.root = op; } if (spec.parent) { var p = ctx.get(spec.parent.$ref); if (p) { df.connect(p, [op]); op.targets().add(p); } else { (ctx.unresolved = ctx.unresolved || []).push(function() { p = ctx.get(spec.parent.$ref); df.connect(p, [op]); op.targets().add(p); }); } } if (spec.signal) { ctx.signals[spec.signal] = op; } if (spec.scale) { ctx.scales[spec.scale] = op; } if (spec.data) { for (var name in spec.data) { data = ctx.data[name] || (ctx.data[name] = {}); spec.data[name].forEach(function(role) { data[role] = op; }); } } }, resolve: function() { (this.unresolved || []).forEach(function(fn) { fn(); }); delete this.unresolved; return this; }, operator: function(spec, update, params) { this.add(spec, this.dataflow.add(spec.value, update, params, spec.react)); }, transform: function(spec, type, params) { this.add(spec, this.dataflow.add(this.transforms[canonicalType(type)], params)); }, stream: function(spec, stream) { this.set(spec.id, stream); }, update: function(spec, stream, target, update, params) { this.dataflow.on(stream, target, update, params, spec.options); }, getState: getState, setState: setState }; var runtime = function(view, spec, functions) { var fn = functions || functionContext; return parseDataflow(spec, context$2(view, transforms, fn)); }; var Padding$1 = 'padding'; function viewWidth(view, width) { var a = view.autosize(), p = view.padding(); return width - (a && a.contains === Padding$1 ? p.left + p.right : 0); } function viewHeight(view, height) { var a = view.autosize(), p = view.padding(); return height - (a && a.contains === Padding$1 ? p.top + p.bottom : 0); } function initializeResize(view) { var s = view._signals, w = s.width, h = s.height, p = s.padding; function resetSize() { view._autosize = view._resize = 1; } // respond to width signal view._resizeWidth = view.add(null, function(_$$1) { view._width = _$$1.size; view._viewWidth = viewWidth(view, _$$1.size); resetSize(); }, {size: w} ); // respond to height signal view._resizeHeight = view.add(null, function(_$$1) { view._height = _$$1.size; view._viewHeight = viewHeight(view, _$$1.size); resetSize(); }, {size: h} ); // respond to padding signal var resizePadding = view.add(null, resetSize, {pad: p}); // set rank to run immediately after source signal view._resizeWidth.rank = w.rank + 1; view._resizeHeight.rank = h.rank + 1; resizePadding.rank = p.rank + 1; } function resizeView(viewWidth, viewHeight, width, height, origin, auto) { this.runAfter(function(view) { var rerun = 0; // reset autosize flag view._autosize = 0; // width value changed: update signal, skip resize op if (view.width() !== width) { rerun = 1; view.width(width); view._resizeWidth.skip(true); } // height value changed: update signal, skip resize op if (view.height() !== height) { rerun = 1; view.height(height); view._resizeHeight.skip(true); } // view width changed: update view property, set resize flag if (view._viewWidth !== viewWidth) { view._resize = 1; view._viewWidth = viewWidth; } // view height changed: update view property, set resize flag if (view._viewHeight !== viewHeight) { view._resize = 1; view._viewHeight = viewHeight; } // origin changed: update view property, set resize flag if (view._origin[0] !== origin[0] || view._origin[1] !== origin[1]) { view._resize = 1; view._origin = origin; } // run dataflow on width/height signal change if (rerun) view.run('enter'); if (auto) view.runAfter(function() { view.resize(); }); }); } /** * Get the current view state, consisting of signal values and/or data sets. * @param {object} [options] - Options flags indicating which state to export. * If unspecified, all signals and data sets will be exported. * @param {function(string, Operator):boolean} [options.signals] - Optional * predicate function for testing if a signal should be included in the * exported state. If unspecified, all signals will be included, except for * those named 'parent' or those which refer to a Transform value. * @param {function(string, object):boolean} [options.data] - Optional * predicate function for testing if a data set's input should be included * in the exported state. If unspecified, all data sets that have been * explicitly modified will be included. * @param {boolean} [options.recurse=true] - Flag indicating if the exported * state should recursively include state from group mark sub-contexts. * @return {object} - An object containing the exported state values. */ function getState$1(options) { return this._runtime.getState(options || { data: dataTest, signals: signalTest, recurse: true }); } function dataTest(name, data) { return data.modified && isArray(data.input.value) && name.indexOf('_:vega:_'); } function signalTest(name, op) { return !(name === 'parent' || op instanceof transforms.proxy); } /** * Sets the current view state and updates the view by invoking run. * @param {object} state - A state object containing signal and/or * data set values, following the format used by the getState method. * @return {View} - This view instance. */ function setState$1(state) { var view = this; view._trigger = false; view._runtime.setState(state); view.run().runAfter(function() { view._trigger = true; }); return this; } /** * Create a new View instance from a Vega dataflow runtime specification. * The generated View will not immediately be ready for display. Callers * should also invoke the initialize method (e.g., to set the parent * DOM element in browser-based deployment) and then invoke the run * method to evaluate the dataflow graph. Rendering will automatically * be peformed upon dataflow runs. * @constructor * @param {object} spec - The Vega dataflow runtime specification. */ function View(spec, options) { var view = this; options = options || {}; Dataflow.call(view); view.loader(options.loader || view._loader); view.logLevel(options.logLevel || 0); view._el = null; view._renderType = options.renderer || RenderType.Canvas; view._scenegraph = new Scenegraph(); var root = view._scenegraph.root; // initialize renderer, handler and event management view._renderer = null; view._redraw = true; view._handler = new CanvasHandler().scene(root); view._eventListeners = []; view._preventDefault = false; // initialize dataflow graph var ctx = runtime(view, spec, options.functions); view._runtime = ctx; view._signals = ctx.signals; view._bind = (spec.bindings || []).map(function(_$$1) { return { state: null, param: extend({}, _$$1) }; }); // initialize scenegraph if (ctx.root) ctx.root.set(root); root.source = ctx.data.root.input; view.pulse( ctx.data.root.input, view.changeset().insert(root.items) ); // initialize background color view._background = ctx.background || null; // initialize event configuration view._eventConfig = initializeEventConfig(ctx.eventConfig); // initialize view size view._width = view.width(); view._height = view.height(); view._viewWidth = viewWidth(view, view._width); view._viewHeight = viewHeight(view, view._height); view._origin = [0, 0]; view._resize = 0; view._autosize = 1; initializeResize(view); // initialize cursor cursor(view); } var prototype$81 = inherits(View, Dataflow); // -- DATAFLOW / RENDERING ---- prototype$81.run = function(encode) { Dataflow.prototype.run.call(this, encode); if (this._redraw || this._resize) { try { this.render(); } catch (e) { this.error(e); } } return this; }; prototype$81.render = function() { if (this._renderer) { if (this._resize) { this._resize = 0; resizeRenderer(this); } this._renderer.render(this._scenegraph.root); } this._redraw = false; return this; }; prototype$81.dirty = function(item) { this._redraw = true; this._renderer && this._renderer.dirty(item); }; // -- GET / SET ---- prototype$81.container = function() { return this._el; }; prototype$81.scenegraph = function() { return this._scenegraph; }; function lookupSignal(view, name) { return view._signals.hasOwnProperty(name) ? view._signals[name] : error$1('Unrecognized signal name: ' + $$2(name)); } prototype$81.signal = function(name, value, options) { var op = lookupSignal(this, name); return arguments.length === 1 ? op.value : this.update(op, value, options); }; prototype$81.background = function(_$$1) { if (arguments.length) { this._background = _$$1; this._resize = 1; return this; } else { return this._background; } }; prototype$81.width = function(_$$1) { return arguments.length ? this.signal('width', _$$1) : this.signal('width'); }; prototype$81.height = function(_$$1) { return arguments.length ? this.signal('height', _$$1) : this.signal('height'); }; prototype$81.padding = function(_$$1) { return arguments.length ? this.signal('padding', _$$1) : this.signal('padding'); }; prototype$81.autosize = function(_$$1) { return arguments.length ? this.signal('autosize', _$$1) : this.signal('autosize'); }; prototype$81.renderer = function(type) { if (!arguments.length) return this._renderType; if (!renderModule(type)) error$1('Unrecognized renderer type: ' + type); if (type !== this._renderType) { this._renderType = type; if (this._renderer) { this._renderer = null; this.initialize(this._el); } } return this; }; prototype$81.loader = function(loader) { if (!arguments.length) return this._loader; if (loader !== this._loader) { Dataflow.prototype.loader.call(this, loader); if (this._renderer) { this._renderer = null; this.initialize(this._el); } } return this; }; prototype$81.resize = function() { this._autosize = 1; return this; }; // -- SIZING ---- prototype$81._resizeView = resizeView; // -- EVENT HANDLING ---- prototype$81.addEventListener = function(type, handler) { this._handler.on(type, handler); return this; }; prototype$81.removeEventListener = function(type, handler) { this._handler.off(type, handler); return this; }; prototype$81.addSignalListener = function(name, handler) { var s = lookupSignal(this, name), h = function() { handler(name, s.value); }; h.handler = handler; this.on(s, null, h); return this; }; prototype$81.removeSignalListener = function(name, handler) { var s = lookupSignal(this, name), t = s._targets || [], h = t.filter(function(op) { var u = op._update; return u && u.handler === handler; }); if (h.length) t.remove(h[0]); return this; }; prototype$81.preventDefault = function(_$$1) { if (arguments.length) { this._preventDefault = _$$1; return this; } else { return this._preventDefault; } }; prototype$81.tooltipHandler = function(_$$1) { var h = this._handler; if (!arguments.length) { return h.handleTooltip; } else { h.handleTooltip = _$$1 || Handler.prototype.handleTooltip; return this; } }; prototype$81.events = events$1; prototype$81.finalize = finalize; prototype$81.hover = hover; // -- DATA ---- prototype$81.data = data; prototype$81.change = change; prototype$81.insert = insert; prototype$81.remove = remove; // -- INITIALIZATION ---- prototype$81.initialize = initialize$1; // -- HEADLESS RENDERING ---- prototype$81.toImageURL = renderToImageURL; prototype$81.toCanvas = renderToCanvas; prototype$81.toSVG = renderToSVG; // -- SAVE / RESTORE STATE ---- prototype$81.getState = getState$1; prototype$81.setState = setState$1; // -- Transforms ----- extend(transforms, tx, vtx, encode, geo, force, tree$1, voronoi$1, wordcloud, xf); exports.version = version; exports.Dataflow = Dataflow; exports.EventStream = EventStream; exports.Parameters = Parameters; exports.Pulse = Pulse; exports.MultiPulse = MultiPulse; exports.Operator = Operator; exports.Transform = Transform; exports.changeset = changeset; exports.ingest = ingest; exports.isTuple = isTuple; exports.definition = definition; exports.transform = transform$1; exports.transforms = transforms; exports.tupleid = tupleid; exports.scale = scale$1; exports.scheme = getScheme; exports.interpolate = interpolate$1; exports.interpolateRange = interpolateRange; exports.timeInterval = timeInterval; exports.utcInterval = utcInterval; exports.projection = projection; exports.View = View; exports.parse = parse$2; exports.expressionFunction = expressionFunction; exports.formatLocale = d3Format.formatDefaultLocale; exports.timeFormatLocale = d3TimeFormat.timeFormatDefaultLocale; exports.runtime = parseDataflow; exports.runtimeContext = context$2; exports.bin = bin; exports.bootstrapCI = bootstrapCI; exports.quartiles = quartiles; exports.setRandom = setRandom; exports.randomInteger = integer; exports.randomKDE = randomKDE; exports.randomMixture = randomMixture; exports.randomNormal = randomNormal; exports.randomUniform = randomUniform; exports.accessor = accessor; exports.accessorName = accessorName; exports.accessorFields = accessorFields; exports.id = id; exports.identity = identity; exports.zero = zero; exports.one = one; exports.truthy = truthy; exports.falsy = falsy; exports.logger = logger; exports.None = None; exports.Error = Error$1; exports.Warn = Warn; exports.Info = Info; exports.Debug = Debug; exports.panLinear = panLinear; exports.panLog = panLog; exports.panPow = panPow; exports.zoomLinear = zoomLinear; exports.zoomLog = zoomLog; exports.zoomPow = zoomPow; exports.array = array; exports.compare = compare; exports.constant = constant; exports.debounce = debounce; exports.error = error$1; exports.extend = extend; exports.extentIndex = extentIndex; exports.fastmap = fastmap; exports.field = field; exports.inherits = inherits; exports.isArray = isArray; exports.isBoolean = isBoolean; exports.isDate = isDate; exports.isFunction = isFunction; exports.isNumber = isNumber; exports.isObject = isObject; exports.isRegExp = isRegExp; exports.isString = isString; exports.key = key; exports.merge = merge; exports.pad = pad; exports.peek = peek; exports.repeat = repeat; exports.splitAccessPath = splitAccessPath; exports.stringValue = $$2; exports.toBoolean = toBoolean; exports.toDate = toDate; exports.toNumber = toNumber; exports.toString = toString; exports.toSet = toSet; exports.truncate = truncate; exports.visitArray = visitArray; exports.loader = loader; exports.read = read; exports.inferType = inferType; exports.inferTypes = inferTypes; exports.typeParsers = typeParsers; exports.formats = formats$1; exports.Bounds = Bounds; exports.Gradient = Gradient; exports.GroupItem = GroupItem; exports.ResourceLoader = ResourceLoader; exports.Item = Item; exports.Scenegraph = Scenegraph; exports.Handler = Handler; exports.Renderer = Renderer; exports.CanvasHandler = CanvasHandler; exports.CanvasRenderer = CanvasRenderer; exports.SVGHandler = SVGHandler; exports.SVGRenderer = SVGRenderer; exports.SVGStringRenderer = SVGStringRenderer; exports.RenderType = RenderType; exports.renderModule = renderModule; exports.Marks = marks; exports.boundContext = context; exports.boundStroke = boundStroke; exports.boundItem = boundItem$1; exports.boundMark = boundMark; exports.pathCurves = curves; exports.pathSymbols = symbols; exports.pathRectangle = vg_rect; exports.pathTrail = vg_trail; exports.pathParse = pathParse; exports.pathRender = pathRender; exports.point = point; exports.canvas = Canvas$1; exports.domCreate = domCreate; exports.domFind = domFind; exports.domChild = domChild; exports.domClear = domClear; exports.openTag = openTag; exports.closeTag = closeTag; exports.font = font; exports.textMetrics = textMetrics; exports.resetSVGClipId = resetSVGClipId; exports.sceneEqual = sceneEqual; exports.pathEqual = pathEqual; exports.sceneToJSON = sceneToJSON; exports.sceneFromJSON = sceneFromJSON; exports.sceneZOrder = zorder; exports.sceneVisit = visit; exports.scenePickVisit = pickVisit; Object.defineProperty(exports, '__esModule', { value: true }); })));
ajax/libs/forerunnerdb/1.3.373/fdb-core+views.min.js
iwdmb/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/View");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/View":31,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":7,"../lib/Shim.IE8":30}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":29}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a,b,c){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c,d){this._store=[],this._keys=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",f),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Sorting"),d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"compareFunc"),d.synthesize(f.prototype,"hashFunc"),d.synthesize(f.prototype,"indexDir"),d.synthesize(f.prototype,"keys"),d.synthesize(f.prototype,"index",function(a){return void 0!==a&&this.keys(this.extractKeys(a)),this.$super.call(this,a)}),f.prototype.extractKeys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},f.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},f.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},f.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),!0}return!1},f.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},f.prototype._hashFunc=function(a){return a[this._keys[0].key]},f.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new f(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},f.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},f.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},f.prototype.findRange=function(a,b,c,d,e){e=e||[],this._left&&this._left.findRange(a,b,c,d,e);var f=this.sortAsc(this._data[b],c),g=this.sortAsc(this._data[b],d);if(!(0!==f&&1!==f||0!==g&&-1!==g))switch(a){case"hash":e.push(this._hash);break;case"data":e.push(this._data);break;default:e.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,e),e},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._index),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}},d.finishModule("BinaryTree"),b.exports=f},{"./Path":26,"./Shared":29}],5:[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,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._metaData={},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"),d.mixin(n.prototype,"Mixin.Updating"),d.mixin(n.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),d.synthesize(n.prototype,"metaData"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!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)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},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 this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(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.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:d},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),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 this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},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":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;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],d,"",{})&&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":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(this._updateIncrement(a,p,b[p]),q=!0);break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" 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],d,"",{})&&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 this.logIdentifier()+" 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 this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(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 this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" 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 this.logIdentifier()+" 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],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),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"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[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.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(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._onChange(),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.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return this.chainSend("insert",a,{index:b}),e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},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=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},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=this.jStringify(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,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H=this._metrics.create("find"),I=this.primaryKey(),J=this,K=!0,L={},M=[],N=[],O=[],P={},Q={},R=function(c){return J._match(c,a,b,"and",P)};if(H.start(),a){if(H.time("analyseQuery"),c=this._analyseQuery(J.decouple(a),b,H),H.time("analyseQuery"),H.data("analysis",c),c.hasJoin&&c.queriesJoin){for(H.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],L[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];H.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(H.data("index.potential",c.indexMatch),H.data("index.used",c.indexMatch[0].index),H.time("indexLookup"),e=c.indexMatch[0].lookup||[],H.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(K=!1)):H.flag("usedIndex",!1),K&&(e&&e.length?(d=e.length,H.time("tableScan: "+d),e=e.filter(R)):(d=this._data.length,H.time("tableScan: "+d),e=this._data.filter(R)),H.time("tableScan: "+d)),b.$orderBy&&(H.time("sort"),e=this.sort(b.$orderBy,e),H.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(Q.page=b.$page,Q.pages=Math.ceil(e.length/b.$limit),Q.records=e.length,b.$page&&b.$limit>0&&(H.data("cursor",Q),e.splice(0,b.$page*b.$limit))),b.$skip&&(Q.skip=b.$skip,e.splice(0,b.$skip),H.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(Q.limit=b.$limit,e.length=b.$limit,H.data("limit",b.$limit)),b.$decouple&&(H.time("decouple"),e=this.decouple(e),H.time("decouple"),H.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=L[k]?L[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=m[n].query),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=J._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else M.push(e[x])}H.data("flag.join",!0)}if(M.length){for(H.time("removalQueue"),z=0;z<M.length;z++)y=e.indexOf(M[z]),y>-1&&e.splice(y,1);H.time("removalQueue")}if(b.$transform){for(H.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));H.time("transform"),H.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(H.time("transformOut"),e=this.transformOut(e),H.time("transformOut")),H.data("results",e.length)}else e=[];H.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?N.push(z):0===b[z]&&O.push(z));if(H.time("scanFields"),N.length||O.length){for(H.data("flag.limitFields",!0),H.data("limitFields.on",N),H.data("limitFields.off",O),H.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(N.length&&A!==I&&-1===N.indexOf(A)&&delete G[A],O.length&&O.indexOf(A)>-1&&delete G[A])}H.time("limitFields")}if(b.$elemMatch){H.data("flag.elemMatch",!0),H.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(J._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}H.time("projection-elemMatch")}if(b.$elemsMatch){H.data("flag.elemsMatch",!0),H.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)J._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}H.time("projection-elemsMatch")}return H.stop(),e.__fdbOp=H,e.$cursor=Q,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g=this;if("string"==typeof a)return"$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b)[0]:new h(a).value(b)[0];c={};for(f in a)if(a.hasOwnProperty(f))switch(d=typeof a[f],e=a[f],d){case"string":"$$."===e.substr(0,3)?c[f]=new h(e.substr(3,e.length-3)).value(b)[0]:c[f]=e;break;case"object":c[f]=g._resolveDynamicQuery(e,b);break;default:c[f]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},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=String(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,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,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 this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},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),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(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(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},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(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;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 this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new 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({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1&&a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}return this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":8,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":29}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":9,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[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}},{}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":13,"./Overload":25,"./Shared":29}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.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",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.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(h.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}},i.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++},i.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--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.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}},i.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},i.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},i.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=i},{"./BinaryTree":4,"./Path":26,"./Shared":29}],11:[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.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":26,"./Shared":29}],12:[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":29}],13:[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":24,"./Shared":29}],14:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],16:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":25,"./Serialiser":28}],17:[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},{}],18:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":25}],19:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){for(k in b)if(b.hasOwnProperty(k)){if(f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++); if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++){if(i[h]instanceof RegExp&&i[h].test(b))return!0;if(i[h]===b)return!0}return!1}throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(l[k]===b)return!1;return!0}throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0}return-1}};b.exports=d},{}],20:[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},{}],21:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],22:[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":25}],23:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],24:[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":26,"./Shared":29}],25:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?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.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":29}],27:[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 this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":29}],28:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],29:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.373",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Tags":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":25}],30:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],31:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.findById=function(a,b){return this.publicData().findById(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b&&!b.isDropped()&&b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;i<c.length;i++)b._privateData._match(c[i],b._querySettings.query,b._querySettings.options,"and",{})&&(f.push(c[i]),g=!0);else b._privateData._match(c,b._querySettings.query,b._querySettings.options,"and",{})&&(f=c,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=b._privateData.diff(b._from.subset(b._querySettings.query,b._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=b._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=b._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var c=a.find(this._querySettings.query,this._querySettings.options);return this._transformPrimaryKey(a.primaryKey()),this._transformSetData(c),this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(c),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i,j,k;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var l=this._from.find(this._querySettings.query,this._querySettings.options);this._transformSetData(l),this._privateData.setData(l);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;k<f.length;k++)h={},i=f[k],h[g]=i[g],this._transformUpdate(h,i);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){return this._privateData.distinct.apply(this._privateData,arguments)},l.prototype.primaryKey=function(){return this._privateData.primaryKey()},l.prototype.drop=function(a){return this.isDropped()?!0:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(l.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},l.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},l.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),b.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.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._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return a instanceof l?a:(this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=l},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":27,"./Shared":29}]},{},[1]);
sample/__tests__/index.ios.js
rnzyn/react-native-credit-card-input
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
TodoWonder/index.ios.js
lintonye/react-native-diary
/** * @flow */ import { AppRegistry, } from 'react-native'; import TodoWonder from './js/TodoWonder' AppRegistry.registerComponent('TodoWonder', () => TodoWonder);
ajax/libs/react-data-grid/0.12.23/react-data-grid.js
pvnr0082t/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactDataGrid"] = factory(require("react")); else root["ReactDataGrid"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Grid = __webpack_require__(43); var Row = __webpack_require__(11); var Cell = __webpack_require__(22); module.exports = Grid; module.exports.Row = Row; module.exports.Cell = Cell; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _classCallCheck = __webpack_require__(17)['default']; var React = __webpack_require__(1); var ExcelColumn = function ExcelColumn() { _classCallCheck(this, ExcelColumn); }; var ExcelColumnShape = { name: React.PropTypes.string.isRequired, key: React.PropTypes.string.isRequired, width: React.PropTypes.number.isRequired }; module.exports = ExcelColumnShape; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var _Object$assign = __webpack_require__(14)["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; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * @providesModule cloneWithProps */ "use strict"; var ReactElement = __webpack_require__(60); var ReactPropTransferer = __webpack_require__(61); var keyOf = __webpack_require__(64); var warning = __webpack_require__(15); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {object} child child component you'd like to clone * @param {object} props props you'd like to modify. They will be merged * as if you used `transferPropsTo()`. * @return {object} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( !child.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactElement.cloneAndReplaceProps. return ReactElement.createElement(child.type, newProps); } module.exports = cloneWithProps; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) /***/ }, /* 6 */ /***/ function(module, exports) { 'use strict'; module.exports = { getColumn: function getColumn(columns, idx) { if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, spliceColumn: function spliceColumn(metrics, idx, column) { if (Array.isArray(metrics.columns)) { metrics.columns.splice(idx, 1, column); } else if (typeof Immutable !== 'undefined') { metrics.columns = metrics.columns.splice(idx, 1, column); } return metrics; }, getSize: function getSize(columns) { if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } } }; /***/ }, /* 7 */ /***/ function(module, exports) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function() { return this; }; emptyFunction.thatReturnsArgument = function(arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 8 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /* TODO mixin and invarient splat */ /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(1); var emptyFunction = __webpack_require__(7); var shallowCloneObject = __webpack_require__(13); var contextTypes = { metricsComputator: React.PropTypes.object }; var MetricsComputatorMixin = { childContextTypes: contextTypes, getChildContext: function getChildContext() { return { metricsComputator: this }; }, getMetricImpl: function getMetricImpl(name) { return this._DOMMetrics.metrics[name].value; }, registerMetricsImpl: function registerMetricsImpl(component, metrics) { var getters = {}; var s = this._DOMMetrics; for (var name in metrics) { if (s.metrics[name] !== undefined) { throw new Error('DOM metric ' + name + ' is already defined'); } s.metrics[name] = { component: component, computator: metrics[name].bind(component) }; getters[name] = this.getMetricImpl.bind(null, name); } if (s.components.indexOf(component) === -1) { s.components.push(component); } return getters; }, unregisterMetricsFor: function unregisterMetricsFor(component) { var s = this._DOMMetrics; var idx = s.components.indexOf(component); if (idx > -1) { s.components.splice(idx, 1); var name; var metricsToDelete = {}; for (name in s.metrics) { if (s.metrics[name].component === component) { metricsToDelete[name] = true; } } for (name in metricsToDelete) { delete s.metrics[name]; } } }, updateMetrics: function updateMetrics() { var s = this._DOMMetrics; var needUpdate = false; for (var name in s.metrics) { var newMetric = s.metrics[name].computator(); if (newMetric !== s.metrics[name].value) { needUpdate = true; } s.metrics[name].value = newMetric; } if (needUpdate) { for (var i = 0, len = s.components.length; i < len; i++) { if (s.components[i].metricsUpdated) { s.components[i].metricsUpdated(); } } } }, componentWillMount: function componentWillMount() { this._DOMMetrics = { metrics: {}, components: [] }; }, componentDidMount: function componentDidMount() { if (window.addEventListener) { window.addEventListener('resize', this.updateMetrics); } else { window.attachEvent('resize', this.updateMetrics); } this.updateMetrics(); }, componentWillUnmount: function componentWillUnmount() { window.removeEventListener('resize', this.updateMetrics); } }; var MetricsMixin = { contextTypes: contextTypes, componentWillMount: function componentWillMount() { if (this.DOMMetrics) { this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics); this.DOMMetrics = {}; for (var name in this._DOMMetricsDefs) { this.DOMMetrics[name] = emptyFunction; } } }, componentDidMount: function componentDidMount() { if (this.DOMMetrics) { this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs); } }, componentWillUnmount: function componentWillUnmount() { if (!this.registerMetricsImpl) { return this.context.metricsComputator.unregisterMetricsFor(this); } if (this.hasOwnProperty('DOMMetrics')) { delete this.DOMMetrics; } }, registerMetrics: function registerMetrics(metrics) { if (this.registerMetricsImpl) { return this.registerMetricsImpl(this, metrics); } else { return this.context.metricsComputator.registerMetricsImpl(this, metrics); } }, getMetric: function getMetric(name) { if (this.getMetricImpl) { return this.getMetricImpl(name); } else { return this.context.metricsComputator.getMetricImpl(name); } } }; module.exports = { MetricsComputatorMixin: MetricsComputatorMixin, MetricsMixin: MetricsMixin }; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* TODO: mixins */ /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(1); var KeyboardHandlerMixin = { onKeyDown: function onKeyDown(e) { if (this.isCtrlKeyHeldDown(e)) { this.checkAndCall('onPressKeyWithCtrl', e); } else if (this.isKeyExplicitlyHandled(e.key)) { //break up individual keyPress events to have their own specific callbacks //this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing var callBack = 'onPress' + e.key; this.checkAndCall(callBack, e); } else if (this.isKeyPrintable(e.keyCode)) { this.checkAndCall('onPressChar', e); } }, //taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character isKeyPrintable: function isKeyPrintable(keycode) { var valid = keycode > 47 && keycode < 58 || // number keys keycode == 32 || keycode == 13 || // spacebar & return key(s) (if you want to allow carriage returns) keycode > 64 && keycode < 91 || // letter keys keycode > 95 && keycode < 112 || // numpad keys keycode > 185 && keycode < 193 || // ;=,-./` (in order) keycode > 218 && keycode < 223; // [\]' (in order) return valid; }, isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) { return typeof this['onPress' + key] === 'function'; }, isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) { return e.ctrlKey === true && e.key !== "Control"; }, checkAndCall: function checkAndCall(methodName, args) { if (typeof this[methodName] === 'function') { this[methodName](args); } } }; module.exports = KeyboardHandlerMixin; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var _extends = __webpack_require__(3)['default']; var React = __webpack_require__(1); var joinClasses = __webpack_require__(4); var Cell = __webpack_require__(22); var cloneWithProps = __webpack_require__(5); var ColumnMetrics = __webpack_require__(12); var ColumnUtilsMixin = __webpack_require__(6); var Row = React.createClass({ displayName: 'Row', propTypes: { height: React.PropTypes.number.isRequired, columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired, row: React.PropTypes.object.isRequired, cellRenderer: React.PropTypes.func, isSelected: React.PropTypes.bool, idx: React.PropTypes.number.isRequired, expandedRows: React.PropTypes.arrayOf(React.PropTypes.object) }, mixins: [ColumnUtilsMixin], render: function render() { var className = joinClasses('react-grid-Row', "react-grid-Row--${this.props.idx % 2 === 0 ? 'even' : 'odd'}"); var style = { height: this.getRowHeight(this.props), overflow: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onDragEnter: this.handleDragEnter }), React.isValidElement(this.props.row) ? this.props.row : cells ); }, getCells: function getCells() { var _this = this; var cells = []; var lockedCells = []; var selectedColumn = this.getSelectedColumn(); this.props.columns.forEach(function (column, i) { var CellRenderer = _this.props.cellRenderer; var cell = React.createElement(CellRenderer, { ref: i, key: i, idx: i, rowIdx: _this.props.idx, value: _this.getCellValue(column.key || i), column: column, height: _this.getRowHeight(), formatter: column.formatter, cellMetaData: _this.props.cellMetaData, rowData: _this.props.row, selectedColumn: selectedColumn, isRowSelected: _this.props.isSelected }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } }); return cells.concat(lockedCells); }, getRowHeight: function getRowHeight() { var rows = this.props.expandedRows || null; if (rows && this.props.key) { var row = rows[this.props.key] || null; if (row) { return row.height; } } return this.props.height; }, getCellValue: function getCellValue(key) { var val; if (key === 'select-row') { return this.props.isSelected; } else if (typeof this.props.row.get === 'function') { val = this.props.row.get(key); } else { val = this.props.row[key]; } return val; }, getRowData: function getRowData() { return this.props.row.toJSON ? this.props.row.toJSON() : this.props.row; }, getDefaultProps: function getDefaultProps() { return { cellRenderer: Cell, isSelected: false, height: 35 }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this2 = this; this.props.columns.forEach(function (column, i) { if (column.locked) { if (!_this2.refs[i]) return; _this2.refs[i].setScrollLeft(scrollLeft); } }); }, doesRowContainSelectedCell: function doesRowContainSelectedCell(props) { var selected = props.cellMetaData.selected; if (selected && selected.rowIdx === props.idx) { return true; } else { return false; } }, willRowBeDraggedOver: function willRowBeDraggedOver(props) { var dragged = props.cellMetaData.dragged; return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true); }, hasRowBeenCopied: function hasRowBeenCopied() { var copied = this.props.cellMetaData.copied; return copied != null && copied.rowIdx === this.props.idx; }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return !ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, ColumnMetrics.sameColumn) || this.doesRowContainSelectedCell(this.props) || this.doesRowContainSelectedCell(nextProps) || this.willRowBeDraggedOver(nextProps) || nextProps.row !== this.props.row || this.hasRowBeenCopied() || this.props.isSelected !== nextProps.isSelected || nextProps.height !== this.props.height; }, handleDragEnter: function handleDragEnter() { var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow; if (handleDragEnterRow) { handleDragEnterRow(this.props.idx); } }, getSelectedColumn: function getSelectedColumn() { var selected = this.props.cellMetaData.selected; if (selected && selected.idx) { return this.getColumn(this.props.columns, selected.idx); } } }); module.exports = Row; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _Object$assign = __webpack_require__(14)['default']; var shallowCloneObject = __webpack_require__(13); var isValidElement = __webpack_require__(1).isValidElement; var sameColumn = __webpack_require__(26); var ColumnUtils = __webpack_require__(6); /** * Update column metrics calculation. * * @param {ColumnMetricsType} metrics */ function recalculate(metrics) { // compute width for columns which specify width var columns = setColumnWidths(metrics.columns, metrics.totalWidth); var unallocatedWidth = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w - column.width; }, metrics.totalWidth); var width = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w + column.width; }, 0); // compute width for columns which doesn't specify width columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth); // compute left offset columns = setColumnOffsets(columns); return { columns: columns, width: width, totalWidth: metrics.totalWidth, minColumnWidth: metrics.minColumnWidth }; } function setColumnOffsets(columns) { var left = 0; return columns.map(function (column) { column.left = left; left += column.width; return column; }); } function setColumnWidths(columns, totalWidth) { return columns.map(function (column) { var colInfo = _Object$assign({}, column); if (column.width) { if (/^([0-9]+)%$/.exec(column.width.toString())) { colInfo.width = Math.floor(column.width / 100 * totalWidth); } } return colInfo; }); } function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) { var defferedColumns = columns.filter(function (c) { return !c.width; }); return columns.map(function (column, i, arr) { if (!column.width) { if (unallocatedWidth <= 0) { column.width = minColumnWidth; } else { column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns)); } } return column; }); } /** * Update column metrics calculation by resizing a column. * * @param {ColumnMetricsType} metrics * @param {Column} column * @param {number} width */ function resizeColumn(metrics, index, width) { var column = ColumnUtils.getColumn(metrics.columns, index); metrics = shallowCloneObject(metrics); metrics.columns = metrics.columns.slice(0); var updatedColumn = shallowCloneObject(column); updatedColumn.width = Math.max(width, metrics.minColumnWidth); metrics = ColumnUtils.spliceColumn(metrics, index, updatedColumn); return recalculate(metrics); } function areColumnsImmutable(prevColumns, nextColumns) { return typeof Immutable !== 'undefined' && prevColumns instanceof Immutable.List && nextColumns instanceof Immutable.List; } function compareEachColumn(prevColumns, nextColumns, sameColumn) { var i, len, column; var prevColumnsByKey = {}; var nextColumnsByKey = {}; if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) { return false; } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; prevColumnsByKey[column.key] = column; } for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) { column = nextColumns[i]; nextColumnsByKey[column.key] = column; var prevColumn = prevColumnsByKey[column.key]; if (prevColumn === undefined || !sameColumn(prevColumn, column)) { return false; } } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; var nextColumn = nextColumnsByKey[column.key]; if (nextColumn === undefined) { return false; } } return true; } function sameColumns(prevColumns, nextColumns, sameColumn) { if (areColumnsImmutable(prevColumns, nextColumns)) { return prevColumns === nextColumns; } else { return compareEachColumn(prevColumns, nextColumns, sameColumn); } } module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns }; /***/ }, /* 13 */ /***/ function(module, exports) { /** * @jsx React.DOM */ 'use strict'; function shallowCloneObject(obj) { var result = {}; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } return result; } module.exports = shallowCloneObject; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(46), __esModule: true }; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ "use strict"; var emptyFunction = __webpack_require__(7); /** * 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 ("production" !== process.env.NODE_ENV) { warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (!condition) { var argIndex = 0; console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];})); } }; } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) /***/ }, /* 16 */ /***/ function(module, exports) { "use strict"; var isFunction = function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }; module.exports = isFunction; /***/ }, /* 17 */ /***/ 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; /***/ }, /* 18 */ /***/ function(module, exports) { var core = module.exports = {}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 19 */ /***/ function(module, exports) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 20 */ /***/ function(module, exports) { /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; }; module.exports = assign; /***/ }, /* 21 */ /***/ function(module, exports) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual */ "use strict"; /** * Performs equality by iterating through keys on an object and returning * false when any key has values which are not strictly equal between * objA and objB. Returns true when the values of all keys are strictly equal. * * @return {boolean} */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } var key; // Test for A's keys different from B. for (key in objA) { if (objA.hasOwnProperty(key) && (!objB.hasOwnProperty(key) || objA[key] !== objB[key])) { return false; } } // Test for B's keys missing from A. for (key in objB) { if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var _extends = __webpack_require__(3)['default']; var React = __webpack_require__(1); var joinClasses = __webpack_require__(4); var cloneWithProps = __webpack_require__(5); var EditorContainer = __webpack_require__(42); var ExcelColumn = __webpack_require__(2); var isFunction = __webpack_require__(16); var CellMetaDataShape = __webpack_require__(34); var Cell = React.createClass({ displayName: 'Cell', propTypes: { rowIdx: React.PropTypes.number.isRequired, idx: React.PropTypes.number.isRequired, selected: React.PropTypes.shape({ idx: React.PropTypes.number.isRequired }), tabIndex: React.PropTypes.number, ref: React.PropTypes.string, column: React.PropTypes.shape(ExcelColumn).isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, isExpanded: React.PropTypes.bool, cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired, handleDragStart: React.PropTypes.func, className: React.PropTypes.string, rowData: React.PropTypes.object.isRequired }, getDefaultProps: function getDefaultProps() { return { tabIndex: -1, ref: "cell", isExpanded: false }; }, getInitialState: function getInitialState() { return { isRowChanging: false, isCellValueChanging: false }; }, componentDidMount: function componentDidMount() { this.checkFocus(); }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { this.checkFocus(); var dragged = this.props.cellMetaData.dragged; if (dragged && dragged.complete === true) { this.props.cellMetaData.handleTerminateDrag(); } if (this.state.isRowChanging && this.props.selectedColumn != null) { this.applyUpdateClass(); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.setState({ isRowChanging: this.props.rowData !== nextProps.rowData, isCellValueChanging: this.props.value !== nextProps.value }); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.rowData !== nextProps.rowData || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected(); }, getStyle: function getStyle() { var style = { position: 'absolute', width: this.props.column.width, height: this.props.height, left: this.props.column.left }; return style; }, render: function render() { var style = this.getStyle(); var className = this.getCellClass(); var cellContent = this.renderCellContent({ value: this.props.value, column: this.props.column, rowIdx: this.props.rowIdx, isExpanded: this.props.isExpanded }); return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onClick: this.onCellClick, onDoubleClick: this.onCellDoubleClick }), cellContent, React.createElement('div', { className: 'drag-handle', draggable: 'true' }) ); }, renderCellContent: function renderCellContent(props) { var CellContent; var Formatter = this.getFormatter(); if (React.isValidElement(Formatter)) { props.dependentValues = this.getFormatterDependencies(); CellContent = cloneWithProps(Formatter, props); } else if (isFunction(Formatter)) { CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() }); } else { CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value }); } return React.createElement( 'div', { ref: 'cell', className: 'react-grid-Cell__value' }, CellContent, ' ', this.props.cellControls ); }, isColumnSelected: function isColumnSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.idx === this.props.idx; }, isSelected: function isSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx; }, isActive: function isActive() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return this.isSelected() && meta.selected.active === true; }, isCellSelectionChanging: function isCellSelectionChanging(nextProps) { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } var nextSelected = nextProps.cellMetaData.selected; if (meta.selected && nextSelected) { return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx; } else { return true; } }, getFormatter: function getFormatter() { var col = this.props.column; if (this.isActive()) { return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height }); } else { return this.props.column.formatter; } }, getRowData: function getRowData() { return this.props.rowData.toJSON ? this.props.rowData.toJSON() : this.props.rowData; }, getFormatterDependencies: function getFormatterDependencies() { //clone row data so editor cannot actually change this var columnName = this.props.column.ItemId; //convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.getRowData(), this.props.column); } }, onCellClick: function onCellClick(e) { var meta = this.props.cellMetaData; if (meta != null && meta.onCellClick != null) { meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, onCellDoubleClick: function onCellDoubleClick(e) { var meta = this.props.cellMetaData; if (meta != null && meta.onCellDoubleClick != null) { meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, checkFocus: function checkFocus() { if (this.isSelected() && !this.isActive()) { this.getDOMNode().focus(); } }, getCellClass: function getCellClass() { var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null); var extraClasses = joinClasses({ 'selected': this.isSelected() && !this.isActive(), 'editing': this.isActive(), 'copied': this.isCopied(), 'active-drag-cell': this.isSelected() || this.isDraggedOver(), 'is-dragged-over-up': this.isDraggedOverUpwards(), 'is-dragged-over-down': this.isDraggedOverDownwards(), 'was-dragged-over': this.wasDraggedOver() }); return joinClasses(className, extraClasses); }, getUpdateCellClass: function getUpdateCellClass() { return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : ''; }, applyUpdateClass: function applyUpdateClass() { var updateCellClass = this.getUpdateCellClass(); // -> removing the class if (updateCellClass != null && updateCellClass != "") { var cellDOMNode = this.getDOMNode(); if (cellDOMNode.classList) { cellDOMNode.classList.remove(updateCellClass); // -> and re-adding the class cellDOMNode.classList.add(updateCellClass); } else if (cellDOMNode.className.indexOf(updateCellClass) === -1) { // IE9 doesn't support classList, nor (I think) altering element.className // without replacing it wholesale. cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass; } } }, setScrollLeft: function setScrollLeft(scrollLeft) { var ctrl = this; //flow on windows has an outdated react declaration, once that gets updated, we can remove this if (ctrl.isMounted()) { var node = this.getDOMNode(); var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.webkitTransform = transform; node.style.transform = transform; } }, isCopied: function isCopied() { var copied = this.props.cellMetaData.copied; return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx; }, isDraggedOver: function isDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx; }, wasDraggedOver: function wasDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx; }, isDraggedCellChanging: function isDraggedCellChanging(nextProps) { var isChanging; var dragged = this.props.cellMetaData.dragged; var nextDragged = nextProps.cellMetaData.dragged; if (dragged) { isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx; return isChanging; } else { return false; } }, isCopyCellChanging: function isCopyCellChanging(nextProps) { var isChanging; var copied = this.props.cellMetaData.copied; var nextCopied = nextProps.cellMetaData.copied; if (copied) { isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx; return isChanging; } else { return false; } }, isDraggedOverUpwards: function isDraggedOverUpwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx; }, isDraggedOverDownwards: function isDraggedOverDownwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx; } }); var SimpleCellFormatter = React.createClass({ displayName: 'SimpleCellFormatter', propTypes: { value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired }, render: function render() { return React.createElement( 'span', null, this.props.value ); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return nextProps.value !== this.props.value; } }); module.exports = Cell; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(1); var CheckboxEditor = React.createClass({ displayName: 'CheckboxEditor', PropTypes: { value: React.PropTypes.bool.isRequired, rowIdx: React.PropTypes.number.isRequired, column: React.PropTypes.shape({ key: React.PropTypes.string.isRequired, onCellChange: React.PropTypes.func.isRequired }).isRequired }, render: function render() { var checked = this.props.value != null ? this.props.value : false; return React.createElement('input', { className: 'react-grid-CheckBox', type: 'checkbox', checked: checked, onClick: this.handleChange }); }, handleChange: function handleChange(e) { this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, e); } }); module.exports = CheckboxEditor; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(1); var keyboardHandlerMixin = __webpack_require__(10); var ExcelColumn = __webpack_require__(2); var SimpleTextEditor = React.createClass({ displayName: 'SimpleTextEditor', propTypes: { value: React.PropTypes.any.isRequired, onBlur: React.PropTypes.func, column: React.PropTypes.shape(ExcelColumn).isRequired }, getValue: function getValue() { var updated = {}; updated[this.props.column.key] = this.refs.input.getDOMNode().value; return updated; }, getInputNode: function getInputNode() { return this.getDOMNode(); }, render: function render() { return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value }); } }); module.exports = SimpleTextEditor; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var React = __webpack_require__(1); var joinClasses = __webpack_require__(4); var PropTypes = React.PropTypes; var cloneWithProps = __webpack_require__(5); var shallowEqual = __webpack_require__(21); var emptyFunction = __webpack_require__(7); var ScrollShim = __webpack_require__(37); var Row = __webpack_require__(11); var ExcelColumn = __webpack_require__(2); var Canvas = React.createClass({ displayName: 'Canvas', mixins: [ScrollShim], propTypes: { rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]), rowHeight: PropTypes.number.isRequired, height: PropTypes.number.isRequired, displayStart: PropTypes.number.isRequired, displayEnd: PropTypes.number.isRequired, rowsCount: PropTypes.number.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]), onRows: PropTypes.func, columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired }, render: function render() { var _this = this; var displayStart = this.state.displayStart; var displayEnd = this.state.displayEnd; var rowHeight = this.props.rowHeight; var length = this.props.rowsCount; var rows = this.getRows(displayStart, displayEnd).map(function (row, idx) { return _this.renderRow({ key: displayStart + idx, ref: idx, idx: displayStart + idx, row: row, height: rowHeight, columns: _this.props.columns, isSelected: _this.isRowSelected(displayStart + idx), expandedRows: _this.props.expandedRows, cellMetaData: _this.props.cellMetaData }); }); this._currentRowsLength = rows.length; if (displayStart > 0) { rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight)); } if (length - displayEnd > 0) { rows.push(this.renderPlaceholder('bottom', (length - displayEnd) * rowHeight)); } var scrollbarWidth = 0; if (this.isMounted()) { // Get the scrollbar width var canvas = this.getDOMNode(); scrollbarWidth = canvas.offsetWidth - canvas.clientWidth; } var style = { position: 'absolute', top: 0, left: 0, overflowX: 'auto', overflowY: 'scroll', width: this.props.totalWidth + scrollbarWidth, height: this.props.height, transform: 'translate3d(0, 0, 0)' }; return React.createElement( 'div', { style: style, onScroll: this.onScroll, className: joinClasses("react-grid-Canvas", this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) }, React.createElement( 'div', { style: { width: this.props.width, overflow: 'hidden' } }, rows ) ); }, renderRow: function renderRow(props) { var RowsRenderer = this.props.rowRenderer; if (typeof RowsRenderer === 'function') { return React.createElement(RowsRenderer, props); } else if (React.isValidElement(this.props.rowRenderer)) { return cloneWithProps(this.props.rowRenderer, props); } }, renderPlaceholder: function renderPlaceholder(key, height) { return React.createElement( 'div', { key: key, style: { height: height } }, this.props.columns.map(function (column, idx) { return React.createElement('div', { style: { width: column.width }, key: idx }); }) ); }, getDefaultProps: function getDefaultProps() { return { rowRenderer: Row, onRows: emptyFunction }; }, isRowSelected: function isRowSelected(rowIdx) { return this.props.selectedRows && this.props.selectedRows[rowIdx] === true; }, _currentRowsLength: 0, _currentRowsRange: { start: 0, end: 0 }, _scroll: { scrollTop: 0, scrollLeft: 0 }, getInitialState: function getInitialState() { return { shouldUpdate: true, displayStart: this.props.displayStart, displayEnd: this.props.displayEnd }; }, componentWillMount: function componentWillMount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentDidMount: function componentDidMount() { this.onRows(); }, componentDidUpdate: function componentDidUpdate(nextProps) { if (this._scroll !== { start: 0, end: 0 }) { this.setScrollLeft(this._scroll.scrollLeft); } this.onRows(); }, componentWillUnmount: function componentWillUnmount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.rowsCount > this.props.rowsCount) { this.getDOMNode().scrollTop = nextProps.rowsCount * this.props.rowHeight; } var shouldUpdate = !(nextProps.visibleStart > this.state.displayStart && nextProps.visibleEnd < this.state.displayEnd) || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || !shallowEqual(nextProps.style, this.props.style); if (shouldUpdate) { this.setState({ shouldUpdate: true, displayStart: nextProps.displayStart, displayEnd: nextProps.displayEnd }); } else { this.setState({ shouldUpdate: false }); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return !nextState || nextState.shouldUpdate; }, onRows: function onRows() { if (this._currentRowsRange !== { start: 0, end: 0 }) { this.props.onRows(this._currentRowsRange); this._currentRowsRange = { start: 0, end: 0 }; } }, getRows: function getRows(displayStart, displayEnd) { this._currentRowsRange = { start: displayStart, end: displayEnd }; if (Array.isArray(this.props.rowGetter)) { return this.props.rowGetter.slice(displayStart, displayEnd); } else { var rows = []; for (var i = displayStart; i < displayEnd; i++) { rows.push(this.props.rowGetter(i)); } return rows; } }, setScrollLeft: function setScrollLeft(scrollLeft) { if (this._currentRowsLength !== 0) { if (!this.refs) return; for (var i = 0, len = this._currentRowsLength; i < len; i++) { if (this.refs[i] && this.refs[i].setScrollLeft) { this.refs[i].setScrollLeft(scrollLeft); } } } }, getScroll: function getScroll() { var _getDOMNode = this.getDOMNode(); var scrollTop = _getDOMNode.scrollTop; var scrollLeft = _getDOMNode.scrollLeft; return { scrollTop: scrollTop, scrollLeft: scrollLeft }; }, onScroll: function onScroll(e) { this.appendScrollShim(); var _e$target = e.target; var scrollTop = _e$target.scrollTop; var scrollLeft = _e$target.scrollLeft; var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft }; this._scroll = scroll; this.props.onScroll(scroll); } }); module.exports = Canvas; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /* TODO objects as a map */ 'use strict'; var isValidElement = __webpack_require__(1).isValidElement; module.exports = function sameColumn(a, b) { var k; for (k in a) { if (a.hasOwnProperty(k)) { if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) { continue; } if (!b.hasOwnProperty(k) || a[k] !== b[k]) { return false; } } } for (k in b) { if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) { return false; } } return true; }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /* TODO mixins */ 'use strict'; var _classCallCheck = __webpack_require__(17)['default']; var ColumnMetrics = __webpack_require__(12); var DOMMetrics = __webpack_require__(9); Object.assign = __webpack_require__(19); var PropTypes = __webpack_require__(1).PropTypes; var ColumnUtils = __webpack_require__(6); var Column = function Column() { _classCallCheck(this, Column); }; ; module.exports = { mixins: [DOMMetrics.MetricsMixin], propTypes: { columns: PropTypes.arrayOf(Column), minColumnWidth: PropTypes.number, columnEquality: PropTypes.func }, DOMMetrics: { gridWidth: function gridWidth() { return this.getDOMNode().offsetWidth - 2; } }, getDefaultProps: function getDefaultProps() { return { minColumnWidth: 80, columnEquality: ColumnMetrics.sameColumn }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.columns) { if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality)) { var columnMetrics = this.createColumnMetrics(); this.setState({ columnMetrics: columnMetrics }); } } }, getTotalWidth: function getTotalWidth() { var totalWidth = 0; if (this.isMounted()) { totalWidth = this.DOMMetrics.gridWidth(); } else { totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth; } return totalWidth; }, getColumnMetricsType: function getColumnMetricsType(metrics) { var totalWidth = this.getTotalWidth(); var currentMetrics = { columns: metrics.columns, totalWidth: totalWidth, minColumnWidth: metrics.minColumnWidth }; var updatedMetrics = ColumnMetrics.recalculate(currentMetrics); return updatedMetrics; }, getColumn: function getColumn(columns, idx) { if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, getSize: function getSize() { var columns = this.state.columnMetrics.columns; if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } }, metricsUpdated: function metricsUpdated() { var columnMetrics = this.createColumnMetrics(); this.setState({ columnMetrics: columnMetrics }); }, createColumnMetrics: function createColumnMetrics(initialRun) { var gridColumns = this.setupGridColumns(); return this.getColumnMetricsType({ columns: gridColumns, minColumnWidth: this.props.minColumnWidth }, initialRun); }, onColumnResize: function onColumnResize(index, width) { var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width); this.setState({ columnMetrics: columnMetrics }); } }; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /* need */ /** * @jsx React.DOM */ 'use strict'; var _extends = __webpack_require__(3)['default']; var React = __webpack_require__(1); var PropTypes = React.PropTypes; var emptyFunction = __webpack_require__(7); var Draggable = React.createClass({ displayName: 'Draggable', propTypes: { onDragStart: PropTypes.func, onDragEnd: PropTypes.func, onDrag: PropTypes.func, component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]) }, render: function render() { var Component = this.props.component; return React.createElement('div', _extends({}, this.props, { onMouseDown: this.onMouseDown, className: 'react-grid-HeaderCell__draggable' })); }, getDefaultProps: function getDefaultProps() { return { onDragStart: emptyFunction.thatReturnsTrue, onDragEnd: emptyFunction, onDrag: emptyFunction }; }, getInitialState: function getInitialState() { return { drag: null }; }, onMouseDown: function onMouseDown(e) { var drag = this.props.onDragStart(e); if (drag === null && e.button !== 0) { return; } window.addEventListener('mouseup', this.onMouseUp); window.addEventListener('mousemove', this.onMouseMove); this.setState({ drag: drag }); }, onMouseMove: function onMouseMove(e) { if (this.state.drag === null) { return; } if (e.preventDefault) { e.preventDefault(); } this.props.onDrag(e); }, onMouseUp: function onMouseUp(e) { this.cleanUp(); this.props.onDragEnd(e, this.state.drag); this.setState({ drag: null }); }, componentWillUnmount: function componentWillUnmount() { this.cleanUp(); }, cleanUp: function cleanUp() { window.removeEventListener('mouseup', this.onMouseUp); window.removeEventListener('mousemove', this.onMouseMove); } }); module.exports = Draggable; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _extends = __webpack_require__(3)['default']; var React = __webpack_require__(1); var PropTypes = React.PropTypes; var Header = __webpack_require__(31); var Viewport = __webpack_require__(38); var ExcelColumn = __webpack_require__(2); var GridScrollMixin = __webpack_require__(30); var DOMMetrics = __webpack_require__(9); var Grid = React.createClass({ displayName: 'Grid', propTypes: { rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), minHeight: PropTypes.number, headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowHeight: PropTypes.number, rowRenderer: PropTypes.func, expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowsCount: PropTypes.number, onRows: PropTypes.func, sortColumn: React.PropTypes.string, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']), rowOffsetHeight: PropTypes.number.isRequired, onViewportKeydown: PropTypes.func.isRequired, onViewportDragStart: PropTypes.func.isRequired, onViewportDragEnd: PropTypes.func.isRequired, onViewportDoubleClick: PropTypes.func.isRequired }, mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin], getStyle: function getStyle() { return { overflow: 'hidden', outline: 0, position: 'relative', minHeight: this.props.minHeight }; }, render: function render() { var headerRows = this.props.headerRows || [{ ref: 'row' }]; return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: 'react-grid-Grid' }), React.createElement(Header, { ref: 'header', columnMetrics: this.props.columnMetrics, onColumnResize: this.props.onColumnResize, height: this.props.rowHeight, totalWidth: this.props.totalWidth, headerRows: headerRows, sortColumn: this.props.sortColumn, sortDirection: this.props.sortDirection, onSort: this.props.onSort }), React.createElement( 'div', { ref: 'viewPortContainer', onKeyDown: this.props.onViewportKeydown, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd }, React.createElement(Viewport, { ref: 'viewport', width: this.props.columnMetrics.width, rowHeight: this.props.rowHeight, rowRenderer: this.props.rowRenderer, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columnMetrics: this.props.columnMetrics, totalWidth: this.props.totalWidth, onScroll: this.onScroll, onRows: this.props.onRows, cellMetaData: this.props.cellMetaData, rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length, minHeight: this.props.minHeight }) ) ); }, getDefaultProps: function getDefaultProps() { return { rowHeight: 35, minHeight: 350 }; } }); module.exports = Grid; /***/ }, /* 30 */ /***/ function(module, exports) { /* TODO mixins */ "use strict"; module.exports = { componentDidMount: function componentDidMount() { this._scrollLeft = this.refs.viewport.getScroll().scrollLeft; this._onScroll(); }, componentDidUpdate: function componentDidUpdate() { this._onScroll(); }, componentWillMount: function componentWillMount() { this._scrollLeft = undefined; }, componentWillUnmount: function componentWillUnmount() { this._scrollLeft = undefined; }, onScroll: function onScroll(props) { if (this._scrollLeft !== props.scrollLeft) { this._scrollLeft = props.scrollLeft; this._onScroll(); } }, _onScroll: function _onScroll() { if (this._scrollLeft !== undefined) { this.refs.header.setScrollLeft(this._scrollLeft); this.refs.viewport.setScrollLeft(this._scrollLeft); } } }; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _extends = __webpack_require__(3)['default']; var React = __webpack_require__(1); var joinClasses = __webpack_require__(4); var shallowCloneObject = __webpack_require__(13); var ColumnMetrics = __webpack_require__(12); var ColumnUtils = __webpack_require__(6); var HeaderRow = __webpack_require__(33); var Header = React.createClass({ displayName: 'Header', propTypes: { columnMetrics: React.PropTypes.shape({ width: React.PropTypes.number.isRequired }).isRequired, totalWidth: React.PropTypes.number, height: React.PropTypes.number.isRequired, headerRows: React.PropTypes.array.isRequired }, render: function render() { var state = this.state.resizing || this.props; var className = joinClasses({ 'react-grid-Header': true, 'react-grid-Header--resizing': !!this.state.resizing }); var headerRows = this.getHeaderRows(); return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: className }), headerRows ); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth != nextProps.totalWidth || this.props.headerRows.length != nextProps.headerRows.length || this.state.resizing != nextState.resizing || this.props.sortColumn != nextProps.sortColumn || this.props.sortDirection != nextProps.sortDirection; return update; }, getHeaderRows: function getHeaderRows() { var columnMetrics = this.getColumnMetrics(); var resizeColumn; if (this.state.resizing) { resizeColumn = this.state.resizing.column; } var headerRows = []; this.props.headerRows.forEach((function (row, index) { var headerRowStyle = { position: 'absolute', top: this.props.height * index, left: 0, width: this.props.totalWidth, overflow: 'hidden' }; headerRows.push(React.createElement(HeaderRow, { key: row.ref, ref: row.ref, style: headerRowStyle, onColumnResize: this.onColumnResize, onColumnResizeEnd: this.onColumnResizeEnd, width: columnMetrics.width, height: row.height || this.props.height, columns: columnMetrics.columns, resizing: resizeColumn, headerCellRenderer: row.headerCellRenderer, sortColumn: this.props.sortColumn, sortDirection: this.props.sortDirection, onSort: this.props.onSort })); }).bind(this)); return headerRows; }, getInitialState: function getInitialState() { return { resizing: null }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.setState({ resizing: null }); }, onColumnResize: function onColumnResize(column, width) { var state = this.state.resizing || this.props; var pos = this.getColumnPosition(column); if (pos != null) { var resizing = { columnMetrics: shallowCloneObject(state.columnMetrics) }; resizing.columnMetrics = ColumnMetrics.resizeColumn(resizing.columnMetrics, pos, width); // we don't want to influence scrollLeft while resizing if (resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) { resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth; } resizing.column = ColumnUtils.getColumn(resizing.columnMetrics.columns, pos); this.setState({ resizing: resizing }); } }, getColumnMetrics: function getColumnMetrics() { var columnMetrics; if (this.state.resizing) { columnMetrics = this.state.resizing.columnMetrics; } else { columnMetrics = this.props.columnMetrics; } return columnMetrics; }, getColumnPosition: function getColumnPosition(column) { var columnMetrics = this.getColumnMetrics(); var pos = -1; columnMetrics.columns.forEach(function (c, idx) { if (c.key === column.key) { pos = idx; } }); return pos === -1 ? null : pos; }, onColumnResizeEnd: function onColumnResizeEnd(column, width) { var pos = this.getColumnPosition(column); if (pos !== null && this.props.onColumnResize) { this.props.onColumnResize(pos, width || column.width); } }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = this.refs.row.getDOMNode(); node.scrollLeft = scrollLeft; this.refs.row.setScrollLeft(scrollLeft); }, getStyle: function getStyle() { return { position: 'relative', height: this.props.height * this.props.headerRows.length, overflow: 'hidden' }; } }); module.exports = Header; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /* TODO unkwon */ /** * @jsx React.DOM */ "use strict"; var React = __webpack_require__(1); var joinClasses = __webpack_require__(4); var cloneWithProps = __webpack_require__(5); var PropTypes = React.PropTypes; var ExcelColumn = __webpack_require__(2); var ResizeHandle = __webpack_require__(35); var HeaderCell = React.createClass({ displayName: 'HeaderCell', propTypes: { renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired, column: PropTypes.shape(ExcelColumn).isRequired, onResize: PropTypes.func.isRequired, height: PropTypes.number.isRequired, onResizeEnd: PropTypes.func.isRequired }, render: function render() { var resizeHandle; if (this.props.column.resizable) { resizeHandle = React.createElement(ResizeHandle, { onDrag: this.onDrag, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd }); } var className = joinClasses({ 'react-grid-HeaderCell': true, 'react-grid-HeaderCell--resizing': this.state.resizing, 'react-grid-HeaderCell--locked': this.props.column.locked }); className = joinClasses(className, this.props.className); var cell = this.getCell(); return React.createElement( 'div', { className: className, style: this.getStyle() }, cell, { resizeHandle: resizeHandle } ); }, getCell: function getCell() { if (React.isValidElement(this.props.renderer)) { return cloneWithProps(this.props.renderer, { column: this.props.column }); } else { return this.props.renderer({ column: this.props.column }); } }, getDefaultProps: function getDefaultProps() { return { renderer: simpleCellRenderer }; }, getInitialState: function getInitialState() { return { resizing: false }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = this.getDOMNode(); node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; }, getStyle: function getStyle() { return { width: this.props.column.width, left: this.props.column.left, display: 'inline-block', position: 'absolute', overflow: 'hidden', height: this.props.height, margin: 0, textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; }, onDragStart: function onDragStart(e) { this.setState({ resizing: true }); //need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, onDrag: function onDrag(e) { var resize = this.props.onResize || null; //for flows sake, doesnt recognise a null check direct if (resize) { var width = this.getWidthFromMouseEvent(e); if (width > 0) { resize(this.props.column, width); } } }, onDragEnd: function onDragEnd(e) { var width = this.getWidthFromMouseEvent(e); this.props.onResizeEnd(this.props.column, width); this.setState({ resizing: false }); }, getWidthFromMouseEvent: function getWidthFromMouseEvent(e) { var right = e.pageX; var left = this.getDOMNode().getBoundingClientRect().left; return right - left; } }); function simpleCellRenderer(props) { return React.createElement( 'div', { className: 'widget-HeaderCell__value' }, props.column.name ); } module.exports = HeaderCell; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _extends = __webpack_require__(3)['default']; var React = __webpack_require__(1); var PropTypes = React.PropTypes; var shallowEqual = __webpack_require__(21); var HeaderCell = __webpack_require__(32); var getScrollbarSize = __webpack_require__(44); var ExcelColumn = __webpack_require__(2); var ColumnUtilsMixin = __webpack_require__(6); var SortableHeaderCell = __webpack_require__(41); var HeaderRowStyle = { overflow: React.PropTypes.string, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: React.PropTypes.number, position: React.PropTypes.string }; var DEFINE_SORT = { ASC: 'ASC', DESC: 'DESC', NONE: 'NONE' }; var HeaderRow = React.createClass({ displayName: 'HeaderRow', propTypes: { width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.number.isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), onColumnResize: PropTypes.func, onSort: PropTypes.func.isRequired, style: PropTypes.shape(HeaderRowStyle) }, mixins: [ColumnUtilsMixin], render: function render() { var cellsStyle = { width: this.props.width ? this.props.width + getScrollbarSize() : '100%', height: this.props.height, whiteSpace: 'nowrap', overflowX: 'hidden', overflowY: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: 'react-grid-HeaderRow' }), React.createElement( 'div', { style: cellsStyle }, cells ) ); }, getHeaderRenderer: function getHeaderRenderer(column) { if (column.sortable) { var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : DEFINE_SORT.NONE; return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection }); } else { return this.props.headerCellRenderer || column.headerRenderer || this.props.cellRenderer; } }, getCells: function getCells() { var cells = []; var lockedCells = []; for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) { var column = this.getColumn(this.props.columns, i); var cell = React.createElement(HeaderCell, { ref: i, key: i, height: this.props.height, column: column, renderer: this.getHeaderRenderer(column), resizing: this.props.resizing === column, onResize: this.props.onColumnResize, onResizeEnd: this.props.onColumnResizeEnd }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } } return cells.concat(lockedCells); }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this = this; this.props.columns.forEach(function (column, i) { if (column.locked) { _this.refs[i].setScrollLeft(scrollLeft); } }); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn != nextProps.sortColumn || this.props.sortDirection != nextProps.sortDirection; }, getStyle: function getStyle() { return { overflow: 'hidden', width: '100%', height: this.props.height, position: 'absolute' }; } }); module.exports = HeaderRow; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var PropTypes = __webpack_require__(1).PropTypes; module.exports = { selected: PropTypes.object.isRequired, copied: PropTypes.object, dragged: PropTypes.object, onCellClick: PropTypes.func.isRequired }; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = __webpack_require__(3)['default']; var React = __webpack_require__(1); var joinClasses = __webpack_require__(4); var Draggable = __webpack_require__(28); var cloneWithProps = __webpack_require__(5); var PropTypes = React.PropTypes; var ResizeHandle = React.createClass({ displayName: 'ResizeHandle', style: { position: 'absolute', top: 0, right: 0, width: 6, height: '100%' }, render: function render() { return React.createElement(Draggable, _extends({}, this.props, { className: 'react-grid-HeaderCell__resizeHandle', style: this.style })); } }); module.exports = ResizeHandle; /***/ }, /* 36 */ /***/ function(module, exports) { 'use strict'; var RowUtils = { get: function get(row, property) { if (typeof row.get === 'function') { return row.get(property); } else { return row[property]; } } }; module.exports = RowUtils; /***/ }, /* 37 */ /***/ function(module, exports) { /* TODO mixin not compatible and HTMLElement classList */ /** * @jsx React.DOM */ 'use strict'; var ScrollShim = { appendScrollShim: function appendScrollShim() { if (!this._scrollShim) { var size = this._scrollShimSize(); var shim = document.createElement('div'); if (shim.classList) { shim.classList.add('react-grid-ScrollShim'); //flow - not compatible with HTMLElement } else { shim.className += ' react-grid-ScrollShim'; } shim.style.position = 'absolute'; shim.style.top = 0; shim.style.left = 0; shim.style.width = size.width + 'px'; shim.style.height = size.height + 'px'; this.getDOMNode().appendChild(shim); this._scrollShim = shim; } this._scheduleRemoveScrollShim(); }, _scrollShimSize: function _scrollShimSize() { return { width: this.props.width, height: this.props.length * this.props.rowHeight }; }, _scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() { if (this._scheduleRemoveScrollShimTimer) { clearTimeout(this._scheduleRemoveScrollShimTimer); } this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200); }, _removeScrollShim: function _removeScrollShim() { if (this._scrollShim) { this._scrollShim.parentNode.removeChild(this._scrollShim); this._scrollShim = undefined; } } }; module.exports = ScrollShim; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(1); var Canvas = __webpack_require__(25); var PropTypes = React.PropTypes; var ViewportScroll = __webpack_require__(39); var Viewport = React.createClass({ displayName: 'Viewport', mixins: [ViewportScroll], propTypes: { rowOffsetHeight: PropTypes.number.isRequired, totalWidth: PropTypes.number.isRequired, columnMetrics: PropTypes.object.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, selectedRows: PropTypes.array, expandedRows: PropTypes.array, rowRenderer: PropTypes.func, rowsCount: PropTypes.number.isRequired, rowHeight: PropTypes.number.isRequired, onRows: PropTypes.func, onScroll: PropTypes.func, minHeight: PropTypes.number }, render: function render() { var style = { padding: 0, bottom: 0, left: 0, right: 0, overflow: 'hidden', position: 'absolute', top: this.props.rowOffsetHeight }; return React.createElement( 'div', { className: 'react-grid-Viewport', style: style }, React.createElement(Canvas, { ref: 'canvas', totalWidth: this.props.totalWidth, width: this.props.columnMetrics.width, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columns: this.props.columnMetrics.columns, rowRenderer: this.props.rowRenderer, visibleStart: this.state.visibleStart, visibleEnd: this.state.visibleEnd, displayStart: this.state.displayStart, displayEnd: this.state.displayEnd, cellMetaData: this.props.cellMetaData, height: this.state.height, rowHeight: this.props.rowHeight, onScroll: this.onScroll, onRows: this.props.onRows }) ); }, getScroll: function getScroll() { return this.refs.canvas.getScroll(); }, onScroll: function onScroll(scroll) { this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount); if (this.props.onScroll) { this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft }); } }, setScrollLeft: function setScrollLeft(scrollLeft) { this.refs.canvas.setScrollLeft(scrollLeft); } }); module.exports = Viewport; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /* TODO mixins */ 'use strict'; var React = __webpack_require__(1); var DOMMetrics = __webpack_require__(9); var getWindowSize = __webpack_require__(45); var PropTypes = React.PropTypes; var min = Math.min; var max = Math.max; var floor = Math.floor; var ceil = Math.ceil; module.exports = { mixins: [DOMMetrics.MetricsMixin], DOMMetrics: { viewportHeight: function viewportHeight() { return this.getDOMNode().offsetHeight; } }, propTypes: { rowHeight: React.PropTypes.number, rowsCount: React.PropTypes.number.isRequired }, getDefaultProps: function getDefaultProps() { return { rowHeight: 30 }; }, getInitialState: function getInitialState() { return this.getGridState(this.props); }, getGridState: function getGridState(props) { var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight); var totalRowCount = min(renderedRowsCount * 2, props.rowsCount); return { displayStart: 0, displayEnd: totalRowCount, height: props.minHeight, scrollTop: 0, scrollLeft: 0 }; }, updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length) { var renderedRowsCount = ceil(height / rowHeight); var visibleStart = floor(scrollTop / rowHeight); var visibleEnd = min(visibleStart + renderedRowsCount, length); var displayStart = max(0, visibleStart - renderedRowsCount * 2); var displayEnd = min(visibleStart + renderedRowsCount * 2, length); var nextScrollState = { visibleStart: visibleStart, visibleEnd: visibleEnd, displayStart: displayStart, displayEnd: displayEnd, height: height, scrollTop: scrollTop, scrollLeft: scrollLeft }; this.setState(nextScrollState); }, metricsUpdated: function metricsUpdated() { var height = this.DOMMetrics.viewportHeight(); if (height) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.rowHeight !== nextProps.rowHeight) { this.setState(this.getGridState(nextProps)); } else if (this.props.rowsCount !== nextProps.rowsCount) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount); } } }; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(1); var ExcelColumn = __webpack_require__(2); var FilterableHeaderCell = React.createClass({ displayName: 'FilterableHeaderCell', propTypes: { onChange: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn).isRequired }, getInitialState: function getInitialState() { return { filterTerm: '' }; }, handleChange: function handleChange(e) { var val = e.target.value; this.setState({ filterTerm: val }); this.props.onChange({ filterTerm: val, columnKey: this.props.column.key }); }, componentDidUpdate: function componentDidUpdate(nextProps) { var ele = this.getDOMNode(); if (ele) ele.focus(); }, render: function render() { return React.createElement( 'div', null, React.createElement( 'div', { className: 'form-group' }, React.createElement(this.renderInput, null) ) ); }, renderInput: function renderInput() { if (this.props.column.filterable === false) { return React.createElement('span', null); } else { return React.createElement('input', { type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange }); } } }); module.exports = FilterableHeaderCell; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(1); var joinClasses = __webpack_require__(4); var ExcelColumn = __webpack_require__(2); var DEFINE_SORT = { ASC: 'ASC', DESC: 'DESC', NONE: 'NONE' }; var SortableHeaderCell = React.createClass({ displayName: 'SortableHeaderCell', propTypes: { columnKey: React.PropTypes.string.isRequired, onSort: React.PropTypes.func.isRequired, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']) }, onClick: function onClick() { var direction; switch (this.props.sortDirection) { case null: case undefined: case DEFINE_SORT.NONE: direction = DEFINE_SORT.ASC; break; case DEFINE_SORT.ASC: direction = DEFINE_SORT.DESC; break; case DEFINE_SORT.DESC: direction = DEFINE_SORT.NONE; break; } this.props.onSort(this.props.columnKey, direction); }, getSortByText: function getSortByText() { var unicodeKeys = { 'ASC': '9650', 'DESC': '9660', 'NONE': '' }; return String.fromCharCode(unicodeKeys[this.props.sortDirection]); }, render: function render() { return React.createElement( 'div', { onClick: this.onClick, style: { cursor: 'pointer' } }, this.props.column.name, React.createElement( 'span', { className: 'pull-right' }, this.getSortByText() ) ); } }); module.exports = SortableHeaderCell; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ 'use strict'; var React = __webpack_require__(1); var joinClasses = __webpack_require__(4); var keyboardHandlerMixin = __webpack_require__(10); var SimpleTextEditor = __webpack_require__(24); var isFunction = __webpack_require__(16); var cloneWithProps = __webpack_require__(5); var EditorContainer = React.createClass({ displayName: 'EditorContainer', mixins: [keyboardHandlerMixin], propTypes: { rowData: React.PropTypes.object.isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, cellMetaData: React.PropTypes.shape({ selected: React.PropTypes.object.isRequired, copied: React.PropTypes.object, dragged: React.PropTypes.object, onCellClick: React.PropTypes.func, onCellDoubleClick: React.PropTypes.func }).isRequired, column: React.PropTypes.object.isRequired, height: React.PropTypes.number.isRequired }, changeCommitted: false, getInitialState: function getInitialState() { return { isInvalid: false }; }, componentDidMount: function componentDidMount() { var inputNode = this.getInputNode(); if (inputNode !== undefined) { this.setTextInputFocus(); if (!this.getEditor().disableContainerStyles) { inputNode.className += ' editor-main'; inputNode.style.height = this.props.height - 1 + 'px'; } } }, createEditor: function createEditor() { var editorProps = { ref: 'editor', name: 'editor', column: this.props.column, value: this.getInitialValue(), onCommit: this.commit, rowMetaData: this.getRowMetaData(), height: this.props.height, onBlur: this.commit, onOverrideKeyDown: this.onKeyDown }; var customEditor = this.props.column.editor; if (customEditor && React.isValidElement(customEditor)) { //return custom column editor or SimpleEditor if none specified return React.addons.cloneWithProps(customEditor, editorProps); } else { return React.createElement(SimpleTextEditor, { ref: 'editor', column: this.props.column, value: this.getInitialValue(), rowMetaData: this.getRowMetaData() }); } }, getRowMetaData: function getRowMetaData() { //clone row data so editor cannot actually change this var columnName = this.props.column.ItemId; //convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.props.rowData, this.props.column); } }, onPressEnter: function onPressEnter(e) { this.commit({ key: 'Enter' }); }, onPressTab: function onPressTab(e) { this.commit({ key: 'Tab' }); }, onPressEscape: function onPressEscape(e) { if (!this.editorIsSelectOpen()) { this.props.cellMetaData.onCommitCancel(); } else { // prevent event from bubbling if editor has results to select e.stopPropagation(); } }, onPressArrowDown: function onPressArrowDown(e) { if (this.editorHasResults()) { //dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowUp: function onPressArrowUp(e) { if (this.editorHasResults()) { //dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowLeft: function onPressArrowLeft(e) { //prevent event propogation. this disables left cell navigation if (!this.isCaretAtBeginningOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, onPressArrowRight: function onPressArrowRight(e) { //prevent event propogation. this disables right cell navigation if (!this.isCaretAtEndOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, editorHasResults: function editorHasResults() { if (this.getEditor().getInputNode().tagName === 'SELECT') { return true; } if (isFunction(this.getEditor().hasResults)) { return this.getEditor().hasResults(); } else { return false; } }, editorIsSelectOpen: function editorIsSelectOpen() { if (isFunction(this.getEditor().isSelectOpen)) { return this.getEditor().isSelectOpen(); } else { return false; } }, getEditor: function getEditor() { //TODO need to check that this.refs.editor conforms to the type //this function is basically just a type cast for the sake of flow return this.refs.editor; }, commit: function commit(args) { var opts = args || {}; var updated = this.getEditor().getValue(); if (this.isNewValueValid(updated)) { var cellKey = this.props.column.key; this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key }); } this.changeCommitted = true; }, isNewValueValid: function isNewValueValid(value) { if (isFunction(this.getEditor().validate)) { var isValid = this.getEditor().validate(value); this.setState({ isInvalid: !isValid }); return isValid; } else { return true; } }, getInputNode: function getInputNode() { return this.getEditor().getInputNode(); }, getInitialValue: function getInitialValue() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; if (keyCode === 'Delete' || keyCode === 'Backspace') { return ''; } else if (keyCode === 'Enter') { return this.props.value; } else { var text = keyCode ? String.fromCharCode(keyCode) : this.props.value; return text; } }, getContainerClass: function getContainerClass() { return joinClasses({ 'has-error': this.state.isInvalid === true }); }, setCaretAtEndOfInput: function setCaretAtEndOfInput() { var input = this.getInputNode(); //taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element var txtLength = input.value.length; if (input.setSelectionRange) { input.setSelectionRange(txtLength, txtLength); } else if (input.createTextRange) { var fieldRange = input.createTextRange(); fieldRange.moveStart('character', txtLength); fieldRange.collapse(); fieldRange.select(); } }, isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0; }, isCaretAtEndOfInput: function isCaretAtEndOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.value.length; }, setTextInputFocus: function setTextInputFocus() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; var inputNode = this.getInputNode(); inputNode.focus(); if (inputNode.tagName === "INPUT") { if (!this.isKeyPrintable(keyCode)) { inputNode.focus(); inputNode.select(); } else { inputNode.select(); } } }, componentWillUnmount: function componentWillUnmount() { if (!this.changeCommitted && !this.hasEscapeBeenPressed()) { this.commit({ key: 'Enter' }); } }, renderStatusIcon: function renderStatusIcon() { if (this.state.isInvalid === true) { return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' }); } }, hasEscapeBeenPressed: function hasEscapeBeenPressed() { var pressed = false; var escapeKey = 27; if (window.event) { if (window.event.keyCode === escapeKey) { pressed = true; } else if (window.event.which === escapeKey) { pressed = true; } } return pressed; }, render: function render() { return React.createElement( 'div', { className: this.getContainerClass(), onKeyDown: this.onKeyDown }, this.createEditor(), this.renderStatusIcon() ); } }); module.exports = EditorContainer; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /** * @jsx React.DOM */ "use strict"; var _extends = __webpack_require__(3)['default']; var _Object$assign = __webpack_require__(14)['default']; var React = __webpack_require__(1); var PropTypes = React.PropTypes; var BaseGrid = __webpack_require__(29); var Row = __webpack_require__(11); var ExcelColumn = __webpack_require__(2); var KeyboardHandlerMixin = __webpack_require__(10); var CheckboxEditor = __webpack_require__(23); var FilterableHeaderCell = __webpack_require__(40); var cloneWithProps = __webpack_require__(5); var DOMMetrics = __webpack_require__(9); var ColumnMetricsMixin = __webpack_require__(27); var RowUtils = __webpack_require__(36); var ColumnUtils = __webpack_require__(6); if (!_Object$assign) { Object.assign = __webpack_require__(19); } var ReactDataGrid = React.createClass({ displayName: 'ReactDataGrid', propTypes: { rowHeight: React.PropTypes.number.isRequired, minHeight: React.PropTypes.number.isRequired, enableRowSelect: React.PropTypes.bool, onRowUpdated: React.PropTypes.func, rowGetter: React.PropTypes.func.isRequired, rowsCount: React.PropTypes.number.isRequired, toolbar: React.PropTypes.element, enableCellSelect: React.PropTypes.bool, columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired, onFilter: React.PropTypes.func, onCellCopyPaste: React.PropTypes.func, onCellsDragged: React.PropTypes.func, onAddFilter: React.PropTypes.func }, mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin], getDefaultProps: function getDefaultProps() { return { enableCellSelect: false, tabIndex: -1, rowHeight: 35, enableRowSelect: false, minHeight: 350 }; }, getInitialState: function getInitialState() { var columnMetrics = this.createColumnMetrics(true); var initialState = { columnMetrics: columnMetrics, selectedRows: this.getInitialSelectedRows(), copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0 }; if (this.props.enableCellSelect) { initialState.selected = { rowIdx: 0, idx: 0 }; } else { initialState.selected = { rowIdx: -1, idx: -1 }; } return initialState; }, getInitialSelectedRows: function getInitialSelectedRows() { var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { selectedRows.push(false); } return selectedRows; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.rowsCount === this.props.rowsCount + 1) { this.onAfterAddRow(nextProps.rowsCount + 1); } }, componentDidMount: function componentDidMount() { var scrollOffset = 0; var canvas = this.getDOMNode().querySelector('.react-grid-Canvas'); if (canvas != null) { scrollOffset = canvas.offsetWidth - canvas.clientWidth; } this.setState({ scrollOffset: scrollOffset }); }, render: function render() { var cellMetaData = { selected: this.state.selected, dragged: this.state.dragged, onCellClick: this.onCellClick, onCellDoubleClick: this.onCellDoubleClick, onCommit: this.onCellCommit, onCommitCancel: this.setInactive, copied: this.state.copied, handleDragEnterRow: this.handleDragEnter, handleTerminateDrag: this.handleTerminateDrag }; var toolbar = this.renderToolbar(); var gridWidth = this.DOMMetrics.gridWidth(); var containerWidth = gridWidth + this.state.scrollOffset; return React.createElement( 'div', { className: 'react-grid-Container', style: { width: containerWidth } }, toolbar, React.createElement( 'div', { className: 'react-grid-Main' }, React.createElement(BaseGrid, _extends({ ref: 'base' }, this.props, { headerRows: this.getHeaderRows(), columnMetrics: this.state.columnMetrics, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, rowHeight: this.props.rowHeight, cellMetaData: cellMetaData, selectedRows: this.state.selectedRows, expandedRows: this.state.expandedRows, rowOffsetHeight: this.getRowOffsetHeight(), sortColumn: this.state.sortColumn, sortDirection: this.state.sortDirection, onSort: this.handleSort, minHeight: this.props.minHeight, totalWidth: gridWidth, onViewportKeydown: this.onKeyDown, onViewportDragStart: this.onDragStart, onViewportDragEnd: this.handleDragEnd, onViewportDoubleClick: this.onViewportDoubleClick, onColumnResize: this.onColumnResize })) ) ); }, renderToolbar: function renderToolbar() { var Toolbar = this.props.toolbar; if (React.isValidElement(Toolbar)) { return cloneWithProps(Toolbar, { onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount }); } }, onSelect: function onSelect(selected) { if (this.props.enableCellSelect) { if (this.state.selected.rowIdx === selected.rowIdx && this.state.selected.idx === selected.idx && this.state.selected.active === true) {} else { var idx = selected.idx; var rowIdx = selected.rowIdx; if (idx >= 0 && rowIdx >= 0 && idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && rowIdx < this.props.rowsCount) { this.setState({ selected: selected }); } } } }, onCellClick: function onCellClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); }, onCellDoubleClick: function onCellDoubleClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); this.setActive('Enter'); }, onViewportDoubleClick: function onViewportDoubleClick(e) { this.setActive(); }, onPressArrowUp: function onPressArrowUp(e) { this.moveSelectedCell(e, -1, 0); }, onPressArrowDown: function onPressArrowDown(e) { this.moveSelectedCell(e, 1, 0); }, onPressArrowLeft: function onPressArrowLeft(e) { this.moveSelectedCell(e, 0, -1); }, onPressArrowRight: function onPressArrowRight(e) { this.moveSelectedCell(e, 0, 1); }, onPressTab: function onPressTab(e) { this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1); }, onPressEnter: function onPressEnter(e) { this.setActive(e.key); }, onPressDelete: function onPressDelete(e) { this.setActive(e.key); }, onPressEscape: function onPressEscape(e) { this.setInactive(e.key); }, onPressBackspace: function onPressBackspace(e) { this.setActive(e.key); }, onPressChar: function onPressChar(e) { if (this.isKeyPrintable(e.keyCode)) { this.setActive(e.keyCode); } }, onPressKeyWithCtrl: function onPressKeyWithCtrl(e) { var keys = { KeyCode_c: 99, KeyCode_C: 67, KeyCode_V: 86, KeyCode_v: 118 }; var idx = this.state.selected.idx; if (this.canEdit(idx)) { if (e.keyCode == keys.KeyCode_c || e.keyCode == keys.KeyCode_C) { var value = this.getSelectedValue(); this.handleCopy({ value: value }); } else if (e.keyCode == keys.KeyCode_v || e.keyCode == keys.KeyCode_V) { this.handlePaste(); } } }, onDragStart: function onDragStart(e) { var value = this.getSelectedValue(); this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: value }); //need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) { // we need to prevent default as we control grid scroll //otherwise it moves every time you left/right which is janky e.preventDefault(); var rowIdx = this.state.selected.rowIdx + rowDelta; var idx = this.state.selected.idx + cellDelta; this.onSelect({ idx: idx, rowIdx: rowIdx }); }, getSelectedValue: function getSelectedValue() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; var cellKey = this.getColumn(this.props.columns, idx).key; var row = this.props.rowGetter(rowIdx); return RowUtils.get(row, cellKey); }, setActive: function setActive(keyPressed) { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && !this.isActive()) { var selected = _Object$assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed }); this.setState({ selected: selected }); } }, setInactive: function setInactive() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && this.isActive()) { var selected = _Object$assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false }); this.setState({ selected: selected }); } }, canEdit: function canEdit(idx) { var col = this.getColumn(this.props.columns, idx); return this.props.enableCellSelect === true && (col.editor != null || col.editable); }, isActive: function isActive() { return this.state.selected.active === true; }, onCellCommit: function onCellCommit(commit) { var selected = _Object$assign({}, this.state.selected); selected.active = false; if (commit.key === 'Tab') { selected.idx += 1; } var expandedRows = this.state.expandedRows; // if(commit.changed && commit.changed.expandedHeight){ // expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight); // } this.setState({ selected: selected, expandedRows: expandedRows }); this.props.onRowUpdated(commit); }, setupGridColumns: function setupGridColumns() { var cols = this.props.columns.slice(0); if (this.props.enableRowSelect) { var selectColumn = { key: 'select-row', name: '', formatter: React.createElement(CheckboxEditor, null), onCellChange: this.handleRowSelect, filterable: false, headerRenderer: React.createElement('input', { type: 'checkbox', onChange: this.handleCheckboxChange }), width: 60, locked: true }; var unshiftedCols = cols.unshift(selectColumn); cols = unshiftedCols > 0 ? cols : unshiftedCols; } return cols; }, handleCheckboxChange: function handleCheckboxChange(e) { var allRowsSelected; if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) { allRowsSelected = true; } else { allRowsSelected = false; } var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { selectedRows.push(allRowsSelected); } this.setState({ selectedRows: selectedRows }); }, // columnKey not used here as this function will select the whole row, // but needed to match the function signature in the CheckboxEditor handleRowSelect: function handleRowSelect(rowIdx, columnKey, e) { e.stopPropagation(); if (this.state.selectedRows != null && this.state.selectedRows.length > 0) { var selectedRows = this.state.selectedRows.slice(); if (selectedRows[rowIdx] == null || selectedRows[rowIdx] == false) { selectedRows[rowIdx] = true; } else { selectedRows[rowIdx] = false; } this.setState({ selectedRows: selectedRows }); } }, //EXPAND ROW Functionality - removing for now till we decide on how best to implement // expandRow(row: Row, newHeight: number): Array<Row>{ // var expandedRows = this.state.expandedRows; // if(expandedRows[row]){ // if(expandedRows[row]== null || expandedRows[row] < newHeight){ // expandedRows[row] = newHeight; // } // }else{ // expandedRows[row] = newHeight; // } // return expandedRows; // }, // // handleShowMore(row: Row, newHeight: number) { // var expandedRows = this.expandRow(row, newHeight); // this.setState({expandedRows : expandedRows}); // }, // // handleShowLess(row: Row){ // var expandedRows = this.state.expandedRows; // if(expandedRows[row]){ // expandedRows[row] = false; // } // this.setState({expandedRows : expandedRows}); // }, // // expandAllRows(){ // // }, // // collapseAllRows(){ // // }, onAfterAddRow: function onAfterAddRow(numberOfRows) { this.setState({ selected: { idx: 1, rowIdx: numberOfRows - 2 } }); }, onToggleFilter: function onToggleFilter() { this.setState({ canFilter: !this.state.canFilter }); }, getHeaderRows: function getHeaderRows() { var rows = [{ ref: "row", height: this.props.rowHeight }]; if (this.state.canFilter === true) { rows.push({ ref: "filterRow", headerCellRenderer: React.createElement(FilterableHeaderCell, { onChange: this.props.onAddFilter, column: this.props.column }), height: 45 }); } return rows; }, getRowOffsetHeight: function getRowOffsetHeight() { var offsetHeight = 0; this.getHeaderRows().forEach(function (row) { return offsetHeight += parseFloat(row.height, 10); }); return offsetHeight; }, handleSort: function handleSort(columnKey, direction) { this.setState({ sortDirection: direction, sortColumn: columnKey }, function () { this.props.onGridSort(columnKey, direction); }); }, copyPasteEnabled: function copyPasteEnabled() { return this.props.onCellCopyPaste !== null; }, handleCopy: function handleCopy(args) { if (!this.copyPasteEnabled()) { return; } var textToCopy = args.value; var selected = this.state.selected; var copied = { idx: selected.idx, rowIdx: selected.rowIdx }; this.setState({ textToCopy: textToCopy, copied: copied }); }, handlePaste: function handlePaste() { if (!this.copyPasteEnabled()) { return; } var selected = this.state.selected; var cellKey = this.getColumn(this.state.columnMetrics.columns, this.state.selected.idx).key; if (this.props.onCellCopyPaste) { this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: selected.rowIdx, value: this.state.textToCopy, fromRow: this.state.copied.rowIdx, toRow: selected.rowIdx }); } this.setState({ copied: null }); }, dragEnabled: function dragEnabled() { return this.props.onCellsDragged !== null; }, handleDragStart: function handleDragStart(dragged) { if (!this.dragEnabled()) { return; } var idx = dragged.idx; var rowIdx = dragged.rowIdx; if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) { this.setState({ dragged: dragged }); } }, handleDragEnter: function handleDragEnter(row) { if (!this.dragEnabled()) { return; } var selected = this.state.selected; var dragged = this.state.dragged; dragged.overRowIdx = row; this.setState({ dragged: dragged }); }, handleDragEnd: function handleDragEnd() { if (!this.dragEnabled()) { return; } var fromRow, toRow; var selected = this.state.selected; var dragged = this.state.dragged; var cellKey = this.getColumn(this.state.columnMetrics.columns, this.state.selected.idx).key; fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; if (this.props.onCellsDragged) { this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value }); } this.setState({ dragged: { complete: true } }); }, handleTerminateDrag: function handleTerminateDrag() { if (!this.dragEnabled()) { return; } this.setState({ dragged: null }); } }); module.exports = ReactDataGrid; /***/ }, /* 44 */ /***/ function(module, exports) { /* offsetWidth in HTMLElement */ "use strict"; var size; function getScrollbarSize() { if (size === undefined) { var outer = document.createElement('div'); outer.style.width = '50px'; outer.style.height = '50px'; outer.style.overflowY = 'scroll'; outer.style.position = 'absolute'; outer.style.top = '-200px'; outer.style.left = '-200px'; var inner = document.createElement('div'); inner.style.height = '100px'; inner.style.width = '100%'; outer.appendChild(inner); document.body.appendChild(outer); var outerWidth = outer.clientWidth; var innerWidth = inner.clientWidth; document.body.removeChild(outer); size = outerWidth - innerWidth; } return size; } module.exports = getScrollbarSize; /***/ }, /* 45 */ /***/ function(module, exports) { /** * @jsx React.DOM */ 'use strict'; /** * Return window's height and width * * @return {Object} height and width of the window */ function getWindowSize() { var width = window.innerWidth; var height = window.innerHeight; if (!width || !height) { width = document.documentElement.clientWidth; height = document.documentElement.clientHeight; } if (!width || !height) { width = document.body.clientWidth; height = document.body.clientHeight; } return { width: width, height: height }; } module.exports = getWindowSize; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(57); module.exports = __webpack_require__(18).Object.assign; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.1 Object.assign(target, source, ...) var toObject = __webpack_require__(56) , IObject = __webpack_require__(54) , enumKeys = __webpack_require__(51); module.exports = __webpack_require__(52)(function(){ return Symbol() in Object.assign({}); // Object.assign available and Symbol is native }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , l = arguments.length , i = 1; while(l > i){ var S = IObject(arguments[i++]) , keys = enumKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; } : Object.assign; /***/ }, /* 48 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(53) , core = __webpack_require__(18) , PROTOTYPE = 'prototype'; var ctx = function(fn, that){ return function(){ return fn.apply(that, arguments); }; }; var $def = function(type, name, source){ var key, own, out, exp , isGlobal = type & $def.G , isProto = type & $def.P , target = isGlobal ? global : type & $def.S ? global[name] : (global[name] || {})[PROTOTYPE] , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // contains in native own = !(type & $def.F) && 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 if(isGlobal && typeof target[key] != 'function')exp = source[key]; // bind timers to global for call from export context else if(type & $def.B && own)exp = ctx(out, global); // wrap global constructors for prevent change them in library else if(type & $def.W && target[key] == out)!function(C){ exp = function(param){ return this instanceof C ? new C(param) : C(param); }; exp[PROTOTYPE] = C[PROTOTYPE]; }(out); else exp = isProto && typeof out == 'function' ? ctx(Function.call, out) : out; // export exports[key] = exp; if(isProto)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out; } }; // type bitmap $def.F = 1; // forced $def.G = 2; // global $def.S = 4; // static $def.P = 8; // proto $def.B = 16; // bind $def.W = 32; // wrap module.exports = $def; /***/ }, /* 50 */ /***/ 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; }; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var $ = __webpack_require__(55); module.exports = function(it){ var keys = $.getKeys(it) , getSymbols = $.getSymbols; if(getSymbols){ var symbols = getSymbols(it) , isEnum = $.isEnum , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key); } return keys; }; /***/ }, /* 52 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 53 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var UNDEFINED = 'undefined'; 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 /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { // indexed object, fallback for non-array-like ES3 strings var cof = __webpack_require__(48); module.exports = 0 in Object('z') ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 55 */ /***/ 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 }; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(50); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $def = __webpack_require__(49); $def($def.S + $def.F, 'Object', {assign: __webpack_require__(47)}); /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactContext */ "use strict"; var assign = __webpack_require__(20); /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: {}, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'}, () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { var result; var previousContext = ReactContext.current; ReactContext.current = assign({}, previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; /***/ }, /* 59 */ /***/ function(module, exports) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @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. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ "use strict"; var ReactContext = __webpack_require__(58); var ReactCurrentOwner = __webpack_require__(59); var warning = __webpack_require__(15); var RESERVED_PROPS = { key: true, ref: true }; /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== process.env.NODE_ENV ? warning( false, 'Don\'t set the ' + key + ' property of the component. ' + 'Mutate the existing props object instead.' ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} element */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {string|object} ref * @param {*} key * @param {*} props * @internal */ var ReactElement = function(type, key, ref, owner, context, props) { // Built-in properties that belong on the element this.type = type; this.key = key; this.ref = ref; // Record the component responsible for creating this element. this._owner = owner; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. this._context = context; if ("production" !== process.env.NODE_ENV) { // The validation flag and props are currently mutative. We put them 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. this._store = { validated: false, props: props }; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(this); return; } } this.props = props; }; // We intentionally don't expose the function on the constructor property. // ReactElement should be indistinguishable from a plain object. ReactElement.prototype = { _isReactElement: true }; if ("production" !== process.env.NODE_ENV) { defineMutationMembrane(ReactElement.prototype); } ReactElement.createElement = function(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( config.key !== null, 'createElement(...): Encountered component with a `key` of null. In ' + 'a future version, this will be treated as equivalent to the string ' + '\'null\'; instead, provide an explicit key or use undefined.' ) : null); } // TODO: Change this back to `config.key === undefined` key = config.key == null ? null : '' + config.key; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return new ReactElement( type, key, ref, ReactCurrentOwner.current, ReactContext.current, props ); }; ReactElement.createFactory = function(type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. <Foo />.type === Foo.type. // 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. factory.type = type; return factory; }; ReactElement.cloneAndReplaceProps = function(oldElement, newProps) { var newElement = new ReactElement( oldElement.type, oldElement.key, oldElement.ref, oldElement._owner, oldElement._context, newProps ); if ("production" !== process.env.NODE_ENV) { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function(object) { // ReactTestUtils is often used outside of beforeEach where as React is // within it. This leads to two different instances of React on the same // page. To identify a element from a different React instance we use // a flag instead of an instanceof check. var isElement = !!(object && object._isReactElement); // if (isElement && !(object instanceof ReactElement)) { // This is an indicator that you're using multiple versions of React at the // same time. This will screw with ownership and stuff. Fix it, please. // TODO: We could possibly warn here. // } return isElement; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ "use strict"; var assign = __webpack_require__(20); var emptyFunction = __webpack_require__(7); var invariant = __webpack_require__(62); var joinClasses = __webpack_require__(63); var warning = __webpack_require__(15); var didWarn = false; /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { TransferStrategies: TransferStrategies, /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); }, /** * @lends {ReactPropTransferer.prototype} */ Mixin: { /** * Transfer props from this component to a target component. * * Props that do not have an explicit transfer strategy will be transferred * only if the target component does not already have the prop set. * * This is usually used to pass down props to a returned root component. * * @param {ReactElement} element Component receiving the properties. * @return {ReactElement} The supplied `component`. * @final * @protected */ transferPropsTo: function(element) { ("production" !== process.env.NODE_ENV ? invariant( element._owner === this, '%s: You can\'t call transferPropsTo() on a component that you ' + 'don\'t own, %s. This usually means you are calling ' + 'transferPropsTo() on a component passed in as props or children.', this.constructor.displayName, typeof element.type === 'string' ? element.type : element.type.displayName ) : invariant(element._owner === this)); if ("production" !== process.env.NODE_ENV) { if (!didWarn) { didWarn = true; ("production" !== process.env.NODE_ENV ? warning( false, 'transferPropsTo is deprecated. ' + 'See http://fb.me/react-transferpropsto for more information.' ) : null); } } // Because elements are immutable we have to merge into the existing // props object rather than clone it. transferInto(element.props, this.props); return element; } } }; module.exports = ReactPropTransferer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if ("production" !== process.env.NODE_ENV) { 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( 'Invariant Violation: ' + format.replace(/%s/g, function() { return args[argIndex++]; }) ); } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8))) /***/ }, /* 63 */ /***/ function(module, exports) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule joinClasses * @typechecks static-only */ "use strict"; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; if (nextClass) { className = (className ? className + ' ' : '') + nextClass; } } } return className; } module.exports = joinClasses; /***/ }, /* 64 */ /***/ function(module, exports) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ } /******/ ]) }); ;
src/components/cv/rating.js
ateixeira/andreteixeira.info
import React from 'react'; import FontAwesome from 'react-fontawesome'; module.exports = React.createClass({ // RENDER render: function() { var rating_bullets = []; [0,1,2,3,4].forEach((i) => { var is_active = i < this.props.level; if (is_active) { rating_bullets.push(<FontAwesome name="circle" />); } else { rating_bullets.push(<FontAwesome name="circle-o" />); } }); return ( <span className="rating fa accent">{rating_bullets}</span> ); } });
src/components/Main.js
lanyulin/react-gallery
require('normalize.css/normalize.css'); require('styles/App.less'); import React from 'react'; import ReactDOM from 'react-dom'; let imagesData = require('../data/imagesData.json'); // 获取图片的地址路径 imagesData = (function getImagesURL(imagesDataArr){ for(var i=0;i<imagesDataArr.length; i++){ let oneImage = imagesDataArr[i]; oneImage.imageURL = require("../images/"+oneImage.fileName); imagesDataArr[i] = oneImage; } return imagesDataArr; })(imagesData); /* * 获取区间内的一个随机值 */ function getRangeRandom(low,high) { return Math.ceil(Math.random() * (high - low) + low) } /* * 获取0-30度之间的任意一个正负值 */ function get30DegRandom(){ return ((Math.random() > 0.5 ? "" : "-") + Math.ceil(Math.random() * 30)) } class ImgFigure extends React.Component{ //imgFigure的点击处理函数 handleClick = (e) => { if(this.props.arrange.isCenter){ this.props.inverse(); }else{ this.props.center(); } e.stopPropagation(); e.preventDefault() }; render(){ var styleObj = {}; //如果props属性中指定了这张图片的位置,则使用 if(this.props.arrange.pos){ styleObj = this.props.arrange.pos; } //如果图片的旋转角度有值且不为0,添加旋转角度 if(this.props.arrange.rotate){ (['MozTransform','msTransform','WebkitTransform','transform']).forEach(value => { styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }) } if(this.props.arrange.isCenter){ styleObj.zIndex = 11 } var imgFigureClassName = "img-figure"; imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : ''; return( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title}/> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p> {this.props.data.desc} </p> </div> </figcaption> </figure> ) } } //控制组件 class ControllerUnit extends React.Component{ handleClick = (e) => { //如果点击的是正在选中的按钮,则翻转图片,否则将对应的图片居中 if(this.props.arrange.isCenter){ this.props.inverse() }else{ this.props.center() } } render(){ var controllerUnitClassName = "controller-unit"; //如果对应的是居中的图片,显示控制按钮的居中态 if(this.props.arrange.isCenter){ controllerUnitClassName += " is-center"; //如果同时对应的是翻转的图片,显示控制按钮的翻转态 if(this.props.arrange.isInverse){ controllerUnitClassName += " is-inverse"; } } return ( <span className={controllerUnitClassName} onClick={this.handleClick}></span> ) } } class AppComponent extends React.Component { constructor(props){ super(props); this.constant = { centerPos:{ left: 0, right: 0 }, hPosRange:{ //水平方向的取值范围 leftSecX:[0,0], rightSecX:[0,0], y: [0,0] }, vPosRange:{ //垂直方向的取值范围 topY:[0,0], x: [0,0] } }; this.state = { imgsArrangeArr : [ /* { pos:{ left:"0", top:"0" }, rotate:0, isInverse: false //正反面 isCenter: false //不居中 }*/ ] } } /* * 翻转图片 * @param index 输入当前被执行inverse操作的图片对应的图片信息数组的index值 * @return {function} 这是一个闭包函数,其内return一个真正待被执行的函数 */ inverse = (index) => { return function () { var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr: imgsArrangeArr }) }.bind(this) }; /* * 重新布局所有图片 * @param centerIndex 指定居中排布哪个图片 */ rearrange = (centerIndex) => { var imgsArrangeArr = this.state.imgsArrangeArr, constant = this.constant, centerPos = constant.centerPos, hPosRange = constant.hPosRange, vPosRange = constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.x, imgsArrangeTopArr = [], topImgNum = Math.floor(Math.random() * 2), //取一个或不取 topImgSpliceIndex = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex ,1); //首先居中centerIndex的图片,居中的图片不需要旋转 imgsArrangeCenterArr[0] = { pos : centerPos, rotate : 0, isCenter: true }; //取出要布局上侧的图片的状态信息 topImgSpliceIndex = Math.ceil(Math.random() * ( imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice( topImgSpliceIndex, topImgNum); //布局位于上侧的图片 imgsArrangeTopArr.forEach((value,index) => { imgsArrangeTopArr[index] = { pos : { top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]), left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]) }, rotate: get30DegRandom(), isCenter:false } }); //布局左右两侧的图片 for(var i=0, j=imgsArrangeArr.length, k = j / 2; i<j; i++){ var hPosRangeLORX = null; //前半部分布局左边,右半部分布局右边 if(i < k){ hPosRangeLORX = hPosRangeLeftSecX; }else{ hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] ={ pos : { top:getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate: get30DegRandom(), isCenter:false } } if(imgsArrangeTopArr && imgsArrangeTopArr[0]){ imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr:imgsArrangeArr }) }; /* * 利用rearrange函数,居中对应的index图片 * @param index,需要被居中的图片对应的图片信息数组的index值 * @return {function} */ center = (index) => { return function () { this.rearrange(index); }.bind(this) } //组件加载完成后,为每张图片计算其位置范围 componentDidMount(){ //拿到舞台的大小 var stageDOM = this.refs.stage, stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); //拿到一个imageFigure的大小 var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0), imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); //计算中心图片的位置点 this.constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH }; //计算左侧、右侧区域图片排布位置的取值范围 this.constant.hPosRange.leftSecX[0] = -halfImgW; this.constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.constant.hPosRange.y[0] = -halfImgH; this.constant.hPosRange.y[1] = stageH - halfImgH; ////计算上侧区域图片排布位置的取值范围 this.constant.vPosRange.topY[0] = -halfImgH; this.constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.constant.vPosRange.x[0] = halfStageW - imgW; this.constant.vPosRange.x[1] = halfStageW; this.rearrange(0); } render() { var controllerUnits = [],imgFigures = []; imagesData.forEach((value,index) => { if(!this.state.imgsArrangeArr[index]){ this.state.imgsArrangeArr[index] = { pos:{ left: 0, top: 0 }, rotate:0, isInverse: false, isCenter: false } } imgFigures.push(<ImgFigure data={value} key={index} ref={"imgFigure"+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} ></ImgFigure>); controllerUnits.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} />); }); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
packages/react-server-website/components/homepage-body.js
lidawang/react-server
import React from 'react'; // import {Component} from 'react'; import Markdown from './Markdown'; import GetStartedSection from './content/HomeGetStartedSection.md'; import WhySection from './content/HomeWhySection.md'; import ContributingSection from './content/HomeContributingSection.md'; import {Link} from "react-server"; import './homepage-body.less'; const HeroSection = () => ( <section className="HeroSection"> <div className="banner-content"> <div className="banner-titles"> <h1 className="banner-title">React Server</h1> <p className="banner-subtitle">Blazing fast page load and seamless navigation.</p> </div> <div className="banner-ctas"> <Link path="/docs" className="Button primary get-started-button">Get Started</Link> <a href="https://github.com/redfin/react-server" className="Button secondary download-button">View on GitHub</a> </div> </div> </section> ) export default class HomepageBody extends React.Component { render() { return ( <div className="HomepageContent"> <HeroSection /> <section className="get-started-section"> <Markdown source={GetStartedSection} /> </section> <section className="why-section"> <Markdown source={WhySection} /> </section> <section className="contributing-section"> <Markdown source={ContributingSection} /> </section> </div> ); } }
day19_todolist_style/src/components/TodoList.js
eyesofkids/ironman2017
//@flow import React from 'react' import TodoItem from './TodoItem' // 預先定義props的結構 type Props = { initText: string, } type Item = { text: string, isCompleted: boolean, } class TodoList extends React.Component { // 預先定義state的結構 state: { items: Array<Item>, inputValue: string, } //建構式 constructor(props: Props) { //super是呼叫上層父類別的建構式 super(props) //設定初始的狀態。注意!這裡有個反樣式。 this.state = { items: [], inputValue:'', } } //處理的方法,用e.target可以獲取到輸入框的值,用箭頭函式可以綁定`this` //輸入文字時 handleChange = (e: Event) => { if (e.target instanceof HTMLInputElement) { this.setState({ inputValue: e.target.value, }) } } //按下Enter時 handleKeyPress = (e: KeyboardEvent) => { if(e.key === 'Enter' && e.target instanceof HTMLInputElement){ //加入新的項目到最前面 //此處有變動 const aItem = {text: e.target.value, isCompleted: false } const newItems = [aItem, ...this.state.items ] //按下enter後,加到列表項目中並清空輸入框 this.setState({ items: newItems, inputValue: '', }) } } // //處理移除掉其中一個陣列中成員的方法 // handleRemoveItem = (index: number) => { // const oldItems = this.state.items // //從陣列中移除一個index的成員的純粹函式 // const newItems = oldItems.slice(0, index).concat(oldItems.slice(index + 1)) // //整個陣列重新更新 // this.setState({ // items: newItems, // }) // } //處理樣式變化其中一個陣列中成員的方法 handleStylingItem = (index: number) => { //拷貝一個新陣列 const newItems = [...this.state.items] //切換isCompleted的布林值 newItems[index].isCompleted = !newItems[index].isCompleted //整個陣列重新更新 this.setState({ items: newItems, }) } //渲染方法,回傳React Element(元素) render() { return ( <div> <input type="text" value={this.state.inputValue} placeholder={this.props.initText} onKeyPress={this.handleKeyPress} onChange={this.handleChange} /> <ul> { this.state.items.map((item, index) => { return <TodoItem key={index} style={item.isCompleted? {color: 'red', textDecoration: 'line-through'} : {color: 'green'}} text={item.text} index={index} onItemClick={this.handleStylingItem} /> }) } </ul> </div> ) } } //加入props的資料類型驗証 TodoList.propTypes = { initText: React.PropTypes.string.isRequired, } //匯出TextInput模組 export default TodoList
src/js/client.js
huangkerui/react-basics
import React from "react"; import ReactDOM from "react-dom"; class Layout extends React.Component<any> { render() { return ( <h1>Hello world!</h1> ); } } ReactDOM.render(<Layout />, document.getElementById('app'));
blueocean-material-icons/src/js/components/svg-icons/action/thumbs-up-down.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionThumbsUpDown = (props) => ( <SvgIcon {...props}> <path d="M12 6c0-.55-.45-1-1-1H5.82l.66-3.18.02-.23c0-.31-.13-.59-.33-.8L5.38 0 .44 4.94C.17 5.21 0 5.59 0 6v6.5c0 .83.67 1.5 1.5 1.5h6.75c.62 0 1.15-.38 1.38-.91l2.26-5.29c.07-.17.11-.36.11-.55V6zm10.5 4h-6.75c-.62 0-1.15.38-1.38.91l-2.26 5.29c-.07.17-.11.36-.11.55V18c0 .55.45 1 1 1h5.18l-.66 3.18-.02.24c0 .31.13.59.33.8l.79.78 4.94-4.94c.27-.27.44-.65.44-1.06v-6.5c0-.83-.67-1.5-1.5-1.5z"/> </SvgIcon> ); ActionThumbsUpDown.displayName = 'ActionThumbsUpDown'; ActionThumbsUpDown.muiName = 'SvgIcon'; export default ActionThumbsUpDown;
ajax/libs/mobx/2.6.5/mobx.min.js
menuka94/cdnjs
/** MobX - (c) Michel Weststrate 2015, 2016 - MIT Licensed */ "use strict";function e(e,n,r,o){return 1===arguments.length&&"function"==typeof e?V(e.name||"<unnamed action>",e):2===arguments.length&&"function"==typeof n?V(e,n):1===arguments.length&&"string"==typeof e?t(e):t(n).apply(null,arguments)}function t(e){return function(t,n,r){return r&&"function"==typeof r.value?(r.value=V(e,r.value),r.enumerable=!1,r.configurable=!0,r):Mt(e).apply(this,arguments)}}function n(e,t,n){var r="string"==typeof e?e:e.name||"<unnamed action>",o="function"==typeof e?e:t,i="function"==typeof e?t:n;return yt("function"==typeof o,"`runInAction` expects a function"),yt(0===o.length,"`runInAction` expects a function without arguments"),yt("string"==typeof r&&r.length>0,"actions should have valid names, got: '"+r+"'"),M(r,o,i,void 0)}function r(e){return"function"==typeof e&&e.isMobxAction===!0}function o(e,t,n){function o(){s(u)}var i,s,a;"string"==typeof e?(i=e,s=t,a=n):"function"==typeof e&&(i=e.name||"Autorun@"+bt(),s=e,a=t),Fe(s,"autorun methods cannot have modifiers"),yt("function"==typeof s,"autorun expects a function"),yt(r(s)===!1,"Warning: attempted to pass an action to autorun. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action."),a&&(s=s.bind(a));var u=new Yt(i,function(){this.track(o)});return u.schedule(),u.getDisposer()}function i(e,t,n,r){var i,s,a,u;"string"==typeof e?(i=e,s=t,a=n,u=r):"function"==typeof e&&(i="When@"+bt(),s=e,a=t,u=n);var c=o(i,function(e){if(s.call(u)){e.dispose();var t=q();a.call(u),Q(t)}});return c}function s(e,t,n){return mt("`autorunUntil` is deprecated, please use `when`."),i.apply(null,arguments)}function a(e,t,n,o){function i(){a(p)}var s,a,u,c;"string"==typeof e?(s=e,a=t,u=n,c=o):"function"==typeof e&&(s=e.name||"AutorunAsync@"+bt(),a=e,u=t,c=n),yt(r(a)===!1,"Warning: attempted to pass an action to autorunAsync. Actions are untracked and will not trigger on state changes. Use `reaction` or wrap only your state modification code in an action."),void 0===u&&(u=1),c&&(a=a.bind(c));var l=!1,p=new Yt(s,function(){l||(l=!0,setTimeout(function(){l=!1,p.isDisposed||p.track(i)},u))});return p.schedule(),p.getDisposer()}function u(t,n,r,o,i,s){function a(){if(!w.isDisposed){var e=!1;w.track(function(){var t=b(w);e=At(y,x,t),x=t}),m&&p&&l(x,w),m||e!==!0||l(x,w),m&&(m=!1)}}var u,c,l,p,f,h;"string"==typeof t?(u=t,c=n,l=r,p=o,f=i,h=s):(u=t.name||n.name||"Reaction@"+bt(),c=t,l=n,p=r,f=o,h=i),void 0===p&&(p=!1),void 0===f&&(f=0);var d=Ue(c,tn.Reference),v=d[0],b=d[1],y=v===tn.Structure;h&&(b=b.bind(h),l=e(u,l.bind(h)));var m=!0,g=!1,x=void 0,w=new Yt(u,function(){f<1?a():g||(g=!0,setTimeout(function(){g=!1,a()},f))});return w.schedule(),w.getDisposer()}function c(e,t,n,r){return("function"==typeof e||Be(e))&&arguments.length<3?"function"==typeof t?l(e,t,void 0):l(e,void 0,t):$t.apply(null,arguments)}function l(e,t,n){var r=Ue(e,tn.Recursive),o=r[0],i=r[1];return new Jt(i,n,o===tn.Structure,i.name,t)}function p(e,t){yt("function"==typeof e&&1===e.length,"createTransformer expects a function that accepts one argument");var n={},r=Xt.resetId,o=function(r){function o(t,n){r.call(this,function(){return e(n)},null,!1,"Transformer-"+e.name+"-"+t,void 0),this.sourceIdentifier=t,this.sourceObject=n}return Vt(o,r),o.prototype.onBecomeUnobserved=function(){var e=this.value;r.prototype.onBecomeUnobserved.call(this),delete n[this.sourceIdentifier],t&&t(e,this.sourceObject)},o}(Jt);return function(e){r!==Xt.resetId&&(n={},r=Xt.resetId);var t=f(e),i=n[t];return i?i.get():(i=n[t]=new o(t,e),i.get())}}function f(e){if(null===e||"object"!=typeof e)throw new Error("[mobx] transform expected some kind of object, got: "+e);var t=e.$transformId;return void 0===t&&(t=bt(),It(e,"$transformId",t)),t}function h(e,t){return J()||console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions."),c(e,t).get()}function d(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return yt(arguments.length>=2,"extendObservable expected 2 or more arguments"),yt("object"==typeof e,"extendObservable expects an object as first argument"),yt(!fn(e),"extendObservable should not be used on maps, use map.merge instead"),t.forEach(function(t){yt("object"==typeof t,"all arguments of extendObservable should be objects"),yt(!O(t),"extending an object with another observable (object) is not supported. Please construct an explicit propertymap, using `toJS` if need. See issue #540"),v(e,t,tn.Recursive,null)}),e}function v(e,t,n,r){var o=Qe(e,r,n);for(var i in t)if(Rt(t,i)){if(e===t&&!jt(e,i))continue;var s=Object.getOwnPropertyDescriptor(t,i);Ze(o,i,s)}return e}function b(e,t){return y(st(e,t))}function y(e){var t={name:e.name};return e.observing&&e.observing.length>0&&(t.dependencies=xt(e.observing).map(y)),t}function m(e,t){return g(st(e,t))}function g(e){var t={name:e.name};return ne(e)&&(t.observers=re(e).map(g)),t}function x(e,t,n){return"function"==typeof n?_(e,t,n):w(e,t)}function w(e,t){return St(e)&&!it(e)?(mt("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),at(R(e)).intercept(t)):at(e).intercept(t)}function _(e,t,n){return St(e)&&!it(e)?(mt("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),d(e,{property:e[t]}),_(e,t,n)):at(e,t).intercept(n)}function S(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(it(e)===!1)return!1;var n=st(e,t);return Gt(n)}return Gt(e)}function O(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(Ye(e)||fn(e))throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");if(it(e)){var n=e.$mobx;return n.values&&!!n.values[t]}return!1}return!!e.$mobx||Ft(e)||Zt(e)||Gt(e)}function A(e,t,n){return yt(arguments.length>=2&&arguments.length<=3,"Illegal decorator config",t),Et(e,t),yt(!n||!n.get,"@observable can not be used on getters, use @computed instead"),Ut.apply(null,arguments)}function R(e,t){if(void 0===e&&(e=void 0),"string"==typeof arguments[1])return A.apply(null,arguments);if(yt(arguments.length<3,"observable expects zero, one or two arguments"),O(e))return e;var n=Ue(e,tn.Recursive),r=n[0],o=n[1],i=r===tn.Reference?Nt.Reference:k(o);switch(i){case Nt.Array:case Nt.PlainObject:return ze(o,r);case Nt.Reference:case Nt.ComplexObject:return new mn(o,r);case Nt.ComplexFunction:throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`");case Nt.ViewFunction:return mt("Use `computed(expr)` instead of `observable(expr)`"),c(e,t)}yt(!1,"Illegal State")}function k(e){return null===e||void 0===e?Nt.Reference:"function"==typeof e?e.length?Nt.ComplexFunction:Nt.ViewFunction:Dt(e)?Nt.Array:"object"==typeof e?St(e)?Nt.PlainObject:Nt.ComplexObject:Nt.Reference}function I(e,t,n,r){return"function"==typeof n?j(e,t,n,r):T(e,t,n)}function T(e,t,n){return St(e)&&!it(e)?(mt("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),at(R(e)).observe(t,n)):at(e).observe(t,n)}function j(e,t,n,r){return St(e)&&!it(e)?(mt("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),d(e,{property:e[t]}),j(e,t,n,r)):at(e,t).observe(n,r)}function E(e,t,n){function r(r){return t&&n.push([e,r]),r}if(void 0===t&&(t=!0),void 0===n&&(n=null),O(e)){if(t&&null===n&&(n=[]),t&&null!==e&&"object"==typeof e)for(var o=0,i=n.length;o<i;o++)if(n[o][0]===e)return n[o][1];if(Ye(e)){var s=r([]),a=e.map(function(e){return E(e,t,n)});s.length=a.length;for(var o=0,i=a.length;o<i;o++)s[o]=a[o];return s}if(it(e)){var s=r({});for(var u in e)s[u]=E(e[u],t,n);return s}if(fn(e)){var c=r({});return e.forEach(function(e,r){return c[r]=E(e,t,n)}),c}if(gn(e))return E(e.get(),t,n)}return e}function L(e,t,n){function r(r){return t&&n.push([e,r]),r}if(void 0===t&&(t=!0),void 0===n&&(n=null),mt("toJSlegacy is deprecated and will be removed in the next major. Use `toJS` instead. See #566"),e instanceof Date||e instanceof RegExp)return e;if(t&&null===n&&(n=[]),t&&null!==e&&"object"==typeof e)for(var o=0,i=n.length;o<i;o++)if(n[o][0]===e)return n[o][1];if(!e)return e;if(Dt(e)){var s=r([]),a=e.map(function(e){return L(e,t,n)});s.length=a.length;for(var o=0,i=a.length;o<i;o++)s[o]=a[o];return s}if(fn(e)){var u=r({});return e.forEach(function(e,r){return u[r]=L(e,t,n)}),u}if(gn(e))return L(e.get(),t,n);if("object"==typeof e){var s=r({});for(var c in e)s[c]=L(e[c],t,n);return s}return e}function C(e,t,n){return void 0===t&&(t=!0),void 0===n&&(n=null),mt("toJSON is deprecated. Use toJS instead"),L.apply(null,arguments)}function P(e){return console.log(e),e}function D(e,t){switch(arguments.length){case 0:if(e=Xt.trackingDerivation,!e)return P("whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly. If you invoked whyRun from inside a computation; the computation is currently suspended but re-evaluating because somebody requested it's value.");break;case 2:e=st(e,t)}return e=st(e),Gt(e)?P(e.whyRun()):Zt(e)?P(e.whyRun()):void yt(!1,"whyRun can only be used on reactions and computed values")}function V(e,t){yt("function"==typeof t,"`action` can only be invoked on functions"),yt("string"==typeof e&&e.length>0,"actions should have valid names, got: '"+e+"'");var n=function(){return M(e,t,this,arguments)};return n.isMobxAction=!0,n}function M(e,t,n,r){yt(!Gt(Xt.trackingDerivation),"Computed values or transformers should not invoke actions or trigger other side effects");var o,i=me();if(i){o=Date.now();var s=r&&r.length||0,a=new Array(s);if(s>0)for(var u=0;u<s;u++)a[u]=r[u];xe({type:"action",name:e,fn:t,target:n,arguments:a})}var c=q();Ae(e,n,!1);var l=B(!0);try{return t.apply(n,r)}finally{z(l),Re(!1),Q(c),i&&we({time:Date.now()-o})}}function $(e){return 0===arguments.length?(mt("`useStrict` without arguments is deprecated, use `isStrictModeEnabled()` instead"),Xt.strictMode):(yt(null===Xt.trackingDerivation,"It is not allowed to set `useStrict` when a derivation is running"),Xt.strictMode=e,Xt.allowStateChanges=!e,void 0)}function U(){return Xt.strictMode}function N(e,t){var n=B(e),r=t();return z(n),r}function B(e){var t=Xt.allowStateChanges;return Xt.allowStateChanges=e,t}function z(e){Xt.allowStateChanges=e}function F(e){switch(e.dependenciesState){case Kt.UP_TO_DATE:return!1;case Kt.NOT_TRACKING:case Kt.STALE:return!0;case Kt.POSSIBLY_STALE:var t=!0,n=q();try{for(var r=e.observing,o=r.length,i=0;i<o;i++){var s=r[i];if(Gt(s)&&(s.get(),e.dependenciesState===Kt.STALE))return t=!1,Q(n),!0}return t=!1,Z(e),Q(n),!1}finally{t&&Z(e)}}}function J(){return null!==Xt.trackingDerivation}function G(){Xt.allowStateChanges||yt(!1,Xt.strictMode?"It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended":"It is not allowed to change the state when a computed value or transformer is being evaluated. Use 'autorun' to create reactive functions with side-effects.")}function K(e,t){Z(e),e.newObserving=new Array(e.observing.length+100),e.unboundDepsCount=0,e.runId=++Xt.runId;var n=Xt.trackingDerivation;Xt.trackingDerivation=e;var r,o=!0;try{r=t.call(e),o=!1}finally{o?W(e):(Xt.trackingDerivation=n,H(e))}return r}function W(e){var t="[mobx] An uncaught exception occurred while calculating your computed value, autorun or transformer. Or inside the render() method of an observer based React component. These functions should never throw exceptions as MobX will not always be able to recover from them. "+("Please fix the error reported after this message or enable 'Pause on (caught) exceptions' in your debugger to find the root cause. In: '"+e.name+"'. ")+"For more details see https://github.com/mobxjs/mobx/issues/462";me()&&ge({type:"error",message:t}),console.warn(t),Z(e),e.newObserving=null,e.unboundDepsCount=0,e.recoverFromError(),ce(),te()}function H(e){var t=e.observing,n=e.observing=e.newObserving;e.newObserving=null;for(var r=0,o=e.unboundDepsCount,i=0;i<o;i++){var s=n[i];0===s.diffValue&&(s.diffValue=1,r!==i&&(n[r]=s),r++)}for(n.length=r,o=t.length;o--;){var s=t[o];0===s.diffValue&&se(s,e),s.diffValue=0}for(;r--;){var s=n[r];1===s.diffValue&&(s.diffValue=0,ie(s,e))}}function X(e){for(var t=e.observing,n=t.length;n--;)se(t[n],e);e.dependenciesState=Kt.NOT_TRACKING,t.length=0}function Y(e){var t=q(),n=e();return Q(t),n}function q(){var e=Xt.trackingDerivation;return Xt.trackingDerivation=null,e}function Q(e){Xt.trackingDerivation=e}function Z(e){if(e.dependenciesState!==Kt.UP_TO_DATE){e.dependenciesState=Kt.UP_TO_DATE;for(var t=e.observing,n=t.length;n--;)t[n].lowestObserverState=Kt.UP_TO_DATE}}function ee(){}function te(){Xt.resetId++;var e=new Ht;for(var t in e)Wt.indexOf(t)===-1&&(Xt[t]=e[t]);Xt.allowStateChanges=!Xt.strictMode}function ne(e){return e.observers&&e.observers.length>0}function re(e){return e.observers}function oe(e){for(var t=e.observers,n=e.observersIndexes,r=t.length,o=0;o<r;o++){var i=t[o].__mapid;o?yt(n[i]===o,"INTERNAL ERROR maps derivation.__mapid to index in list"):yt(!(i in n),"INTERNAL ERROR observer on index 0 shouldnt be held in map.")}yt(0===t.length||Object.keys(n).length===t.length-1,"INTERNAL ERROR there is no junk in map")}function ie(e,t){var n=e.observers.length;n&&(e.observersIndexes[t.__mapid]=n),e.observers[n]=t,e.lowestObserverState>t.dependenciesState&&(e.lowestObserverState=t.dependenciesState)}function se(e,t){if(1===e.observers.length)e.observers.length=0,ae(e);else{var n=e.observers,r=e.observersIndexes,o=n.pop();if(o!==t){var i=r[t.__mapid]||0;i?r[o.__mapid]=i:delete r[o.__mapid],n[i]=o}delete r[t.__mapid]}}function ae(e){e.isPendingUnobservation||(e.isPendingUnobservation=!0,Xt.pendingUnobservations.push(e))}function ue(){Xt.inBatch++}function ce(){if(1===Xt.inBatch){for(var e=Xt.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation=!1,0===n.observers.length&&n.onBecomeUnobserved()}Xt.pendingUnobservations=[]}Xt.inBatch--}function le(e){var t=Xt.trackingDerivation;null!==t?t.runId!==e.lastAccessedBy&&(e.lastAccessedBy=t.runId,t.newObserving[t.unboundDepsCount++]=e):0===e.observers.length&&ae(e)}function pe(e,t){var n=re(e).reduce(function(e,t){return Math.min(e,t.dependenciesState)},2);if(!(n>=e.lowestObserverState))throw new Error("lowestObserverState is wrong for "+t+" because "+n+" < "+e.lowestObserverState)}function fe(e){if(e.lowestObserverState!==Kt.STALE){e.lowestObserverState=Kt.STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Kt.UP_TO_DATE&&r.onBecomeStale(),r.dependenciesState=Kt.STALE}}}function he(e){if(e.lowestObserverState!==Kt.STALE){e.lowestObserverState=Kt.STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Kt.POSSIBLY_STALE?r.dependenciesState=Kt.STALE:r.dependenciesState===Kt.UP_TO_DATE&&(e.lowestObserverState=Kt.UP_TO_DATE)}}}function de(e){if(e.lowestObserverState===Kt.UP_TO_DATE){e.lowestObserverState=Kt.POSSIBLY_STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Kt.UP_TO_DATE&&(r.dependenciesState=Kt.POSSIBLY_STALE,r.onBecomeStale())}}}function ve(){Xt.isRunningReactions===!0||Xt.inTransaction>0||Qt(be)}function be(){Xt.isRunningReactions=!0;for(var e=Xt.pendingReactions,t=0;e.length>0;){if(++t===qt)throw te(),new Error("Reaction doesn't converge to a stable state after "+qt+" iterations. Probably there is a cycle in the reactive function: "+e[0]);for(var n=e.splice(0),r=0,o=n.length;r<o;r++)n[r].runReaction()}Xt.isRunningReactions=!1}function ye(e){var t=Qt;Qt=function(n){return e(function(){return t(n)})}}function me(){return!!Xt.spyListeners.length}function ge(e){if(!Xt.spyListeners.length)return!1;for(var t=Xt.spyListeners,n=0,r=t.length;n<r;n++)t[n](e)}function xe(e){var t=Ot({},e,{spyReportStart:!0});ge(t)}function we(e){ge(e?Ot({},e,en):en)}function _e(e){return Xt.spyListeners.push(e),gt(function(){var t=Xt.spyListeners.indexOf(e);t!==-1&&Xt.spyListeners.splice(t,1)})}function Se(e){return mt("trackTransitions is deprecated. Use mobx.spy instead"),"boolean"==typeof e&&(mt("trackTransitions only takes a single callback function. If you are using the mobx-react-devtools, please update them first"),e=arguments[1]),e?_e(e):(mt("trackTransitions without callback has been deprecated and is a no-op now. If you are using the mobx-react-devtools, please update them first"),function(){})}function Oe(e,t,n){void 0===t&&(t=void 0),void 0===n&&(n=!0),Ae(e.name||"anonymous transaction",t,n);try{return e.call(t)}finally{Re(n)}}function Ae(e,t,n){void 0===t&&(t=void 0),void 0===n&&(n=!0),ue(),Xt.inTransaction+=1,n&&me()&&xe({type:"transaction",target:t,name:e})}function Re(e){void 0===e&&(e=!0),0===--Xt.inTransaction&&ve(),e&&me()&&we(),ce()}function ke(e){return e.interceptors&&e.interceptors.length>0}function Ie(e,t){var n=e.interceptors||(e.interceptors=[]);return n.push(t),gt(function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Te(e,t){var n=q();try{for(var r=e.interceptors,o=0,i=r.length;o<i&&(t=r[o](t),yt(!t||t.type,"Intercept handlers should return nothing or a change object"),t);o++);return t}finally{Q(n)}}function je(e){return e.changeListeners&&e.changeListeners.length>0}function Ee(e,t){var n=e.changeListeners||(e.changeListeners=[]);return n.push(t),gt(function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Le(e,t){var n=q(),r=e.changeListeners;if(r){r=r.slice();for(var o=0,i=r.length;o<i;o++)Array.isArray(t)?r[o].apply(null,t):r[o](t);Q(n)}}function Ce(e,t){return Fe(t,"Modifiers are not allowed to be nested"),{mobxModifier:e,value:t}}function Pe(e){return e?e.mobxModifier||null:null}function De(e){return Ce(tn.Reference,e)}function Ve(e){return Ce(tn.Structure,e)}function Me(e){return Ce(tn.Flat,e)}function $e(e,t){return qe(e,t)}function Ue(e,t){var n=Pe(e);return n?[n,e.value]:[t,e]}function Ne(e){if(void 0===e)return tn.Recursive;var t=Pe(e);return yt(null!==t,"Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: "+e),t}function Be(e){return void 0!==e.mobxModifier}function ze(e,t,n){var r;if(O(e))return e;switch(t){case tn.Reference:return e;case tn.Flat:Fe(e,"Items inside 'asFlat' cannot have modifiers"),r=tn.Reference;break;case tn.Structure:Fe(e,"Items inside 'asStructure' cannot have modifiers"),r=tn.Structure;break;case tn.Recursive:o=Ue(e,tn.Recursive),r=o[0],e=o[1];break;default:yt(!1,"Illegal State")}return Array.isArray(e)?He(e,r,n):St(e)&&Object.isExtensible(e)?v(e,e,r,n):e;var o}function Fe(e,t){if(null!==Pe(e))throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. "+t)}function Je(e){var t=Ge(e),n=Ke(e);Object.defineProperty(an.prototype,""+e,{enumerable:!1,configurable:!0,set:t,get:n})}function Ge(e){return function(t){var n=this.$mobx,r=n.values;if(Fe(t,"Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array))."),e<r.length){G();var o=r[e];if(ke(n)){var i=Te(n,{type:"update",object:n.array,index:e,newValue:t});if(!i)return;t=i.newValue}t=n.makeReactiveArrayItem(t);var s=n.mode===tn.Structure?!Ct(o,t):o!==t;s&&(r[e]=t,n.notifyArrayChildUpdate(e,t,o))}else{if(e!==r.length)throw new Error("[mobx.array] Index out of bounds, "+e+" is larger than "+r.length);n.spliceWithArray(e,0,[t])}}}function Ke(e){return function(){var t=this.$mobx;return t&&e<t.values.length?(t.atom.reportObserved(),t.values[e]):void console.warn("[mobx.array] Attempt to read an array index ("+e+") that is out of bounds ("+t.values.length+"). Please check length first. Out of bound indices will not be tracked by MobX")}}function We(e){for(var t=rn;t<e;t++)Je(t);rn=e}function He(e,t,n){return new an(e,t,n)}function Xe(e){return mt("fastArray is deprecated. Please use `observable(asFlat([]))`"),He(e,tn.Flat,null)}function Ye(e){return _t(e)&&cn(e.$mobx)}function qe(e,t){return new pn(e,t)}function Qe(e,t,n){if(void 0===n&&(n=tn.Recursive),it(e))return e.$mobx;St(e)||(t=e.constructor.name+"@"+bt()),t||(t="ObservableObject@"+bt());var r=new hn(e,t,n);return Tt(e,"$mobx",r),r}function Ze(e,t,n){e.values[t]?(yt("value"in n,"cannot redefine property "+t),e.target[t]=n.value):"value"in n?et(e,t,n.value,!0,void 0):et(e,t,n.get,!0,n.set)}function et(e,t,n,o,i){o&&Et(e.target,t);var s,a=e.name+"."+t,u=!0;if(Gt(n))s=n,n.name=a,n.scope||(n.scope=e.target);else if("function"!=typeof n||0!==n.length||r(n))if(Pe(n)===tn.Structure&&"function"==typeof n.value&&0===n.value.length)s=new Jt(n.value,e.target,(!0),a,i);else{if(u=!1,ke(e)){var c=Te(e,{object:e.target,name:t,type:"add",newValue:n});if(!c)return;n=c.newValue}s=new mn(n,e.mode,a,(!1)),n=s.value}else s=new Jt(n,e.target,(!1),a,i);e.values[t]=s,o&&Object.defineProperty(e.target,t,u?nt(t):tt(t)),u||ot(e,e.target,t,n)}function tt(e){var t=dn[e];return t?t:dn[e]={configurable:!0,enumerable:!0,get:function(){return this.$mobx.values[e].get()},set:function(t){rt(this,e,t)}}}function nt(e){var t=vn[e];return t?t:vn[e]={configurable:!0,enumerable:!1,get:function(){return this.$mobx.values[e].get()},set:function(t){return this.$mobx.values[e].set(t)}}}function rt(e,t,n){var r=e.$mobx,o=r.values[t];if(ke(r)){var i=Te(r,{type:"update",object:e,name:t,newValue:n});if(!i)return;n=i.newValue}if(n=o.prepareNewValue(n),n!==yn){var s=je(r),a=me(),i=s||a?{type:"update",object:e,oldValue:o.value,name:t,newValue:n}:null;a&&xe(i),o.setNewValue(n),s&&Le(r,i),a&&we()}}function ot(e,t,n,r){var o=je(e),i=me(),s=o||i?{type:"add",object:t,name:n,newValue:r}:null;i&&xe(s),o&&Le(e,s),i&&we()}function it(e){return!!_t(e)&&(pt(e),bn(e.$mobx))}function st(e,t){if("object"==typeof e&&null!==e){if(Ye(e))return yt(void 0===t,"It is not possible to get index atoms from arrays"),e.$mobx.atom;if(fn(e)){if(void 0===t)return st(e._keys);var n=e._data[t]||e._hasMap[t];return yt(!!n,"the entry '"+t+"' does not exist in the observable map '"+ut(e)+"'"),n}if(pt(e),it(e)){yt(!!t,"please specify a property");var r=e.$mobx.values[t];return yt(!!r,"no observable property '"+t+"' found on the observable object '"+ut(e)+"'"),r}if(Ft(e)||Gt(e)||Zt(e))return e}else if("function"==typeof e&&Zt(e.$mobx))return e.$mobx;yt(!1,"Cannot obtain atom from "+e)}function at(e,t){return yt(e,"Expecting some object"),void 0!==t?at(st(e,t)):Ft(e)||Gt(e)||Zt(e)?e:fn(e)?e:(pt(e),e.$mobx?e.$mobx:void yt(!1,"Cannot obtain administration from "+e))}function ut(e,t){var n;return n=void 0!==t?st(e,t):it(e)||fn(e)?at(e):st(e),n.name}function ct(e,t,n,r,o){function i(i,s,a,u,c){if(yt(o||ft(arguments),"This function is a decorator, but it wasn't invoked like a decorator"),a){Rt(i,"__mobxLazyInitializers")||It(i,"__mobxLazyInitializers",i.__mobxLazyInitializers&&i.__mobxLazyInitializers.slice()||[]);var l=a.value,p=a.initializer;return i.__mobxLazyInitializers.push(function(t){e(t,s,p?p.call(t):l,u,a)}),{enumerable:r,configurable:!0,get:function(){return this.__mobxDidRunLazyInitializers!==!0&&pt(this),t.call(this,s)},set:function(e){this.__mobxDidRunLazyInitializers!==!0&&pt(this),n.call(this,s,e)}}}var f={enumerable:r,configurable:!0,get:function(){return this.__mobxInitializedProps&&this.__mobxInitializedProps[s]===!0||lt(this,s,void 0,e,u,a),t.call(this,s)},set:function(t){this.__mobxInitializedProps&&this.__mobxInitializedProps[s]===!0?n.call(this,s,t):lt(this,s,t,e,u,a)}};return(arguments.length<3||5===arguments.length&&c<3)&&Object.defineProperty(i,s,f),f}return o?function(){if(ft(arguments))return i.apply(null,arguments);var e=arguments,t=arguments.length;return function(n,r,o){return i(n,r,o,e,t)}}:i}function lt(e,t,n,r,o,i){Rt(e,"__mobxInitializedProps")||It(e,"__mobxInitializedProps",{}),e.__mobxInitializedProps[t]=!0,r(e,t,n,o,i)}function pt(e){e.__mobxDidRunLazyInitializers!==!0&&e.__mobxLazyInitializers&&(It(e,"__mobxDidRunLazyInitializers",!0),e.__mobxDidRunLazyInitializers&&e.__mobxLazyInitializers.forEach(function(t){return t(e)}))}function ft(e){return(2===e.length||3===e.length)&&"string"==typeof e[1]}function ht(){return"function"==typeof Symbol&&Symbol.iterator||"@@iterator"}function dt(e){yt(e[xn]!==!0,"Illegal state: cannot recycle array as iterator"),Tt(e,xn,!0);var t=-1;return Tt(e,"next",function(){return t++,{done:t>=this.length,value:t<this.length?this[t]:void 0}}),e}function vt(e,t){Tt(e,ht(),t)}function bt(){return++Xt.mobxGuid}function yt(e,t,n){if(!e)throw new Error("[mobx] Invariant failed: "+t+(n?" in '"+n+"'":""))}function mt(e){Sn.indexOf(e)===-1&&(Sn.push(e),console.error("[mobx] Deprecated: "+e))}function gt(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function xt(e){var t=[];return e.forEach(function(e){t.indexOf(e)===-1&&t.push(e)}),t}function wt(e,t,n){if(void 0===t&&(t=100),void 0===n&&(n=" - "),!e)return"";var r=e.slice(0,t);return""+r.join(n)+(e.length>t?" (... and "+(e.length-t)+"more)":"")}function _t(e){return null!==e&&"object"==typeof e}function St(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function Ot(){for(var e=arguments[0],t=1,n=arguments.length;t<n;t++){var r=arguments[t];for(var o in r)Rt(r,o)&&(e[o]=r[o])}return e}function At(e,t,n){return e?!Ct(t,n):t!==n}function Rt(e,t){return An.call(e,t)}function kt(e,t){for(var n=0;n<t.length;n++)It(e,t[n],e[t[n]])}function It(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function Tt(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function jt(e,t){var n=Object.getOwnPropertyDescriptor(e,t);return!n||n.configurable!==!1&&n.writable!==!1}function Et(e,t){yt(jt(e,t),"Cannot make property '"+t+"' observable, it is not configurable and writable in the target object")}function Lt(e){var t=[];for(var n in e)t.push(n);return t}function Ct(e,t){if(null===e&&null===t)return!0;if(void 0===e&&void 0===t)return!0;var n=Dt(e);if(n!==Dt(t))return!1;if(n){if(e.length!==t.length)return!1;for(var r=e.length-1;r>=0;r--)if(!Ct(e[r],t[r]))return!1;return!0}if("object"==typeof e&&"object"==typeof t){if(null===e||null===t)return!1;if(Lt(e).length!==Lt(t).length)return!1;for(var o in e){if(!(o in t))return!1;if(!Ct(e[o],t[o]))return!1}return!0}return e===t}function Pt(e,t){var n="isMobX"+e;return t.prototype[n]=!0,function(e){return _t(e)&&e[n]===!0}}function Dt(e){return Array.isArray(e)||Ye(e)}var Vt=this&&this.__extends||function(e,t){function n(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)};ee(),exports.extras={allowStateChanges:N,getAtom:st,getDebugName:ut,getDependencyTree:b,getObserverTree:m,isComputingDerivation:J,isSpyEnabled:me,resetGlobalState:te,spyReport:ge,spyReportEnd:we,spyReportStart:xe,trackTransitions:Se,setReactionScheduler:ye},exports._={getAdministration:at,resetGlobalState:te},"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx(module.exports);var Mt=ct(function(t,n,r,o,i){var s=o&&1===o.length?o[0]:r.name||n||"<unnamed action>",a=e(s,r);It(t,n,a)},function(e){return this[e]},function(){yt(!1,"It is not allowed to assign new values to @action fields")},!1,!0);exports.action=e,exports.runInAction=n,exports.isAction=r,exports.autorun=o,exports.when=i,exports.autorunUntil=s,exports.autorunAsync=a,exports.reaction=u;var $t=ct(function(e,t,n,r,o){yt("undefined"!=typeof o,"@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'. It looks like it was used on a property.");var i=o.get,s=o.set;yt("function"==typeof i,"@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'");var a=!1;r&&1===r.length&&r[0].asStructure===!0&&(a=!0);var u=Qe(e,void 0,tn.Recursive);et(u,t,a?Ve(i):i,!1,s)},function(e){var t=this.$mobx.values[e];if(void 0!==t)return t.get()},function(e,t){this.$mobx.values[e].set(t)},!1,!0);exports.computed=c,exports.createTransformer=p,exports.expr=h,exports.extendObservable=d,exports.intercept=x,exports.isComputed=S,exports.isObservable=O;var Ut=ct(function(e,t,n){var r=B(!0);"function"==typeof n&&(n=De(n));var o=Qe(e,void 0,tn.Recursive);et(o,t,n,!0,void 0),z(r)},function(e){var t=this.$mobx.values[e];if(void 0!==t)return t.get()},function(e,t){rt(this,e,t)},!0,!1);exports.observable=R;var Nt;!function(e){e[e.Reference=0]="Reference",e[e.PlainObject=1]="PlainObject",e[e.ComplexObject=2]="ComplexObject",e[e.Array=3]="Array",e[e.ViewFunction=4]="ViewFunction",e[e.ComplexFunction=5]="ComplexFunction"}(Nt||(Nt={})),exports.observe=I,exports.toJS=E,exports.toJSlegacy=L,exports.toJSON=C,exports.whyRun=D,exports.useStrict=$,exports.isStrictModeEnabled=U;var Bt=function(){function e(e){void 0===e&&(e="Atom@"+bt()),this.name=e,this.isPendingUnobservation=!0,this.observers=[],this.observersIndexes={},this.diffValue=0,this.lastAccessedBy=0,this.lowestObserverState=Kt.NOT_TRACKING}return e.prototype.onBecomeUnobserved=function(){},e.prototype.reportObserved=function(){le(this)},e.prototype.reportChanged=function(){Ae("propagatingAtomChange",null,!1),fe(this),Re(!1)},e.prototype.toString=function(){return this.name},e}();exports.BaseAtom=Bt;var zt=function(e){function t(t,n,r){void 0===t&&(t="Atom@"+bt()),void 0===n&&(n=On),void 0===r&&(r=On),e.call(this,t),this.name=t,this.onBecomeObservedHandler=n,this.onBecomeUnobservedHandler=r,this.isPendingUnobservation=!1,this.isBeingTracked=!1}return Vt(t,e),t.prototype.reportObserved=function(){return ue(),e.prototype.reportObserved.call(this),this.isBeingTracked||(this.isBeingTracked=!0,this.onBecomeObservedHandler()),ce(),!!Xt.trackingDerivation},t.prototype.onBecomeUnobserved=function(){this.isBeingTracked=!1,this.onBecomeUnobservedHandler()},t}(Bt);exports.Atom=zt;var Ft=Pt("Atom",Bt),Jt=function(){function e(e,t,n,r,o){this.derivation=e,this.scope=t,this.compareStructural=n,this.dependenciesState=Kt.NOT_TRACKING,this.observing=[],this.newObserving=null,this.isPendingUnobservation=!1,this.observers=[],this.observersIndexes={},this.diffValue=0,this.runId=0,this.lastAccessedBy=0,this.lowestObserverState=Kt.UP_TO_DATE,this.unboundDepsCount=0,this.__mapid="#"+bt(),this.value=void 0,this.isComputing=!1,this.isRunningSetter=!1,this.name=r||"ComputedValue@"+bt(),o&&(this.setter=V(r+"-setter",o))}return e.prototype.peek=function(){this.isComputing=!0;var e=B(!1),t=this.derivation.call(this.scope);return z(e),this.isComputing=!1,t},e.prototype.peekUntracked=function(){var e=!0;try{var t=this.peek();return e=!1,t}finally{e&&W(this)}},e.prototype.onBecomeStale=function(){de(this)},e.prototype.onBecomeUnobserved=function(){yt(this.dependenciesState!==Kt.NOT_TRACKING,"INTERNAL ERROR only onBecomeUnobserved shouldn't be called twice in a row"),X(this),this.value=void 0},e.prototype.get=function(){yt(!this.isComputing,"Cycle detected in computation "+this.name,this.derivation),ue(),1===Xt.inBatch?F(this)&&(this.value=this.peekUntracked()):(le(this),F(this)&&this.trackAndCompute()&&he(this));var e=this.value;return ce(),e},e.prototype.recoverFromError=function(){this.isComputing=!1},e.prototype.set=function(e){if(this.setter){yt(!this.isRunningSetter,"The setter of computed value '"+this.name+"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"),this.isRunningSetter=!0;try{this.setter.call(this.scope,e)}finally{this.isRunningSetter=!1}}else yt(!1,"[ComputedValue '"+this.name+"'] It is not possible to assign a new value to a computed value.")},e.prototype.trackAndCompute=function(){me()&&ge({object:this,type:"compute",fn:this.derivation,target:this.scope});var e=this.value,t=this.value=K(this,this.peek);return At(this.compareStructural,t,e)},e.prototype.observe=function(e,t){var n=this,r=!0,i=void 0;return o(function(){var o=n.get();if(!r||t){var s=q();e(o,i),Q(s)}r=!1,i=o})},e.prototype.toJSON=function(){ return this.get()},e.prototype.toString=function(){return this.name+"["+this.derivation.toString()+"]"},e.prototype.whyRun=function(){var e=Boolean(Xt.trackingDerivation),t=xt(this.isComputing?this.newObserving:this.observing).map(function(e){return e.name}),n=xt(re(this).map(function(e){return e.name}));return"\nWhyRun? computation '"+this.name+"':\n * Running because: "+(e?"[active] the value of this computation is needed by a reaction":this.isComputing?"[get] The value of this computed was requested outside a reaction":"[idle] not running at the moment")+"\n"+(this.dependenciesState===Kt.NOT_TRACKING?" * This computation is suspended (not in use by any reaction) and won't run automatically.\n\tDidn't expect this computation to be suspended at this point?\n\t 1. Make sure this computation is used by a reaction (reaction, autorun, observer).\n\t 2. Check whether you are using this computation synchronously (in the same stack as they reaction that needs it).\n":" * This computation will re-run if any of the following observables changes:\n "+wt(t)+"\n "+(this.isComputing&&e?" (... or any observable accessed during the remainder of the current run)":"")+"\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n * If the outcome of this computation changes, the following observers will be re-run:\n "+wt(n)+"\n")},e}(),Gt=Pt("ComputedValue",Jt),Kt;!function(e){e[e.NOT_TRACKING=-1]="NOT_TRACKING",e[e.UP_TO_DATE=0]="UP_TO_DATE",e[e.POSSIBLY_STALE=1]="POSSIBLY_STALE",e[e.STALE=2]="STALE"}(Kt||(Kt={})),exports.IDerivationState=Kt,exports.untracked=Y;var Wt=["mobxGuid","resetId","spyListeners","strictMode","runId"],Ht=function(){function e(){this.version=4,this.trackingDerivation=null,this.runId=0,this.mobxGuid=0,this.inTransaction=0,this.isRunningReactions=!1,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.allowStateChanges=!0,this.strictMode=!1,this.resetId=0,this.spyListeners=[]}return e}(),Xt=function(){var e=new Ht;if(global.__mobservableTrackingStack||global.__mobservableViewStack)throw new Error("[mobx] An incompatible version of mobservable is already loaded.");if(global.__mobxGlobal&&global.__mobxGlobal.version!==e.version)throw new Error("[mobx] An incompatible version of mobx is already loaded.");return global.__mobxGlobal?global.__mobxGlobal:global.__mobxGlobal=e}(),Yt=function(){function e(e,t){void 0===e&&(e="Reaction@"+bt()),this.name=e,this.onInvalidate=t,this.observing=[],this.newObserving=[],this.dependenciesState=Kt.NOT_TRACKING,this.diffValue=0,this.runId=0,this.unboundDepsCount=0,this.__mapid="#"+bt(),this.isDisposed=!1,this._isScheduled=!1,this._isTrackPending=!1,this._isRunning=!1}return e.prototype.onBecomeStale=function(){this.schedule()},e.prototype.schedule=function(){this._isScheduled||(this._isScheduled=!0,Xt.pendingReactions.push(this),ue(),ve(),ce())},e.prototype.isScheduled=function(){return this._isScheduled},e.prototype.runReaction=function(){this.isDisposed||(this._isScheduled=!1,F(this)&&(this._isTrackPending=!0,this.onInvalidate(),this._isTrackPending&&me()&&ge({object:this,type:"scheduled-reaction"})))},e.prototype.track=function(e){ue();var t,n=me();n&&(t=Date.now(),xe({object:this,type:"reaction",fn:e})),this._isRunning=!0,K(this,e),this._isRunning=!1,this._isTrackPending=!1,this.isDisposed&&X(this),n&&we({time:Date.now()-t}),ce()},e.prototype.recoverFromError=function(){this._isRunning=!1,this._isTrackPending=!1},e.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this._isRunning||(ue(),X(this),ce()))},e.prototype.getDisposer=function(){var e=this.dispose.bind(this);return e.$mobx=this,e},e.prototype.toString=function(){return"Reaction["+this.name+"]"},e.prototype.whyRun=function(){var e=xt(this._isRunning?this.newObserving:this.observing).map(function(e){return e.name});return"\nWhyRun? reaction '"+this.name+"':\n * Status: ["+(this.isDisposed?"stopped":this._isRunning?"running":this.isScheduled()?"scheduled":"idle")+"]\n * This reaction will re-run if any of the following observables changes:\n "+wt(e)+"\n "+(this._isRunning?" (... or any observable accessed during the remainder of the current run)":"")+"\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n"},e}();exports.Reaction=Yt;var qt=100,Qt=function(e){return e()},Zt=Pt("Reaction",Yt),en={spyReportEnd:!0};exports.spy=_e,exports.transaction=Oe;var tn;!function(e){e[e.Recursive=0]="Recursive",e[e.Reference=1]="Reference",e[e.Structure=2]="Structure",e[e.Flat=3]="Flat"}(tn||(tn={})),exports.ValueMode=tn,exports.asReference=De,De.mobxModifier=tn.Reference,exports.asStructure=Ve,Ve.mobxModifier=tn.Structure,exports.asFlat=Me,Me.mobxModifier=tn.Flat,exports.asMap=$e;var nn=function(){var e=!1,t={};return Object.defineProperty(t,"0",{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),rn=0,on=function(){function e(){}return e}();on.prototype=[];var sn=function(){function e(e,t,n,r){this.mode=t,this.array=n,this.owned=r,this.lastKnownLength=0,this.interceptors=null,this.changeListeners=null,this.atom=new Bt(e||"ObservableArray@"+bt())}return e.prototype.makeReactiveArrayItem=function(e){return Fe(e,"Array values cannot have modifiers"),this.mode===tn.Flat||this.mode===tn.Reference?e:ze(e,this.mode,this.atom.name+"[..]")},e.prototype.intercept=function(e){return Ie(this,e)},e.prototype.observe=function(e,t){return void 0===t&&(t=!1),t&&e({object:this.array,type:"splice",index:0,added:this.values.slice(),addedCount:this.values.length,removed:[],removedCount:0}),Ee(this,e)},e.prototype.getArrayLength=function(){return this.atom.reportObserved(),this.values.length},e.prototype.setArrayLength=function(e){if("number"!=typeof e||e<0)throw new Error("[mobx.array] Out of range: "+e);var t=this.values.length;e!==t&&(e>t?this.spliceWithArray(t,0,new Array(e-t)):this.spliceWithArray(e,t-e))},e.prototype.updateArrayLength=function(e,t){if(e!==this.lastKnownLength)throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?");this.lastKnownLength+=t,t>0&&e+t+1>rn&&We(e+t+1)},e.prototype.spliceWithArray=function(e,t,n){G();var r=this.values.length;if(void 0===e?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=1===arguments.length?r-e:void 0===t||null===t?0:Math.max(0,Math.min(t,r-e)),void 0===n&&(n=[]),ke(this)){var o=Te(this,{object:this.array,type:"splice",index:e,removedCount:t,added:n});if(!o)return _n;t=o.removedCount,n=o.added}n=n.map(this.makeReactiveArrayItem,this);var i=n.length-t;this.updateArrayLength(r,i);var s=(a=this.values).splice.apply(a,[e,t].concat(n));return 0===t&&0===n.length||this.notifyArraySplice(e,n,s),s;var a},e.prototype.notifyArrayChildUpdate=function(e,t,n){var r=!this.owned&&me(),o=je(this),i=o||r?{object:this.array,type:"update",index:e,newValue:t,oldValue:n}:null;r&&xe(i),this.atom.reportChanged(),o&&Le(this,i),r&&we()},e.prototype.notifyArraySplice=function(e,t,n){var r=!this.owned&&me(),o=je(this),i=o||r?{object:this.array,type:"splice",index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&xe(i),this.atom.reportChanged(),o&&Le(this,i),r&&we()},e}(),an=function(e){function t(t,n,r,o){void 0===o&&(o=!1),e.call(this);var i=new sn(r,n,this,o);Tt(this,"$mobx",i),t&&t.length?(i.updateArrayLength(0,t.length),i.values=t.map(i.makeReactiveArrayItem,i),i.notifyArraySplice(0,i.values.slice(),_n)):i.values=[],nn&&Object.defineProperty(i.array,"0",un)}return Vt(t,e),t.prototype.intercept=function(e){return this.$mobx.intercept(e)},t.prototype.observe=function(e,t){return void 0===t&&(t=!1),this.$mobx.observe(e,t)},t.prototype.clear=function(){return this.splice(0)},t.prototype.concat=function(){for(var e=[],t=0;t<arguments.length;t++)e[t-0]=arguments[t];return this.$mobx.atom.reportObserved(),Array.prototype.concat.apply(this.slice(),e.map(function(e){return Ye(e)?e.slice():e}))},t.prototype.replace=function(e){return this.$mobx.spliceWithArray(0,this.$mobx.values.length,e)},t.prototype.toJS=function(){return this.slice()},t.prototype.toJSON=function(){return this.toJS()},t.prototype.peek=function(){return this.$mobx.values},t.prototype.find=function(e,t,n){void 0===n&&(n=0),this.$mobx.atom.reportObserved();for(var r=this.$mobx.values,o=r.length,i=n;i<o;i++)if(e.call(t,r[i],i,this))return r[i]},t.prototype.splice=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];switch(arguments.length){case 0:return[];case 1:return this.$mobx.spliceWithArray(e);case 2:return this.$mobx.spliceWithArray(e,t)}return this.$mobx.spliceWithArray(e,t,n)},t.prototype.push=function(){for(var e=[],t=0;t<arguments.length;t++)e[t-0]=arguments[t];var n=this.$mobx;return n.spliceWithArray(n.values.length,0,e),n.values.length},t.prototype.pop=function(){return this.splice(Math.max(this.$mobx.values.length-1,0),1)[0]},t.prototype.shift=function(){return this.splice(0,1)[0]},t.prototype.unshift=function(){for(var e=[],t=0;t<arguments.length;t++)e[t-0]=arguments[t];var n=this.$mobx;return n.spliceWithArray(0,0,e),n.values.length},t.prototype.reverse=function(){this.$mobx.atom.reportObserved();var e=this.slice();return e.reverse.apply(e,arguments)},t.prototype.sort=function(e){this.$mobx.atom.reportObserved();var t=this.slice();return t.sort.apply(t,arguments)},t.prototype.remove=function(e){var t=this.$mobx.values.indexOf(e);return t>-1&&(this.splice(t,1),!0)},t.prototype.move=function(e,t){function n(e){if(e<0)throw new Error("[mobx.array] Index out of bounds: "+e+" is negative");var t=this.$mobx.values.length;if(e>=t)throw new Error("[mobx.array] Index out of bounds: "+e+" is not smaller than "+t)}if(n.call(this,e),n.call(this,t),e!==t){var r,o=this.$mobx.values;r=e<t?o.slice(0,e).concat(o.slice(e+1,t+1),[o[e]],o.slice(t+1)):o.slice(0,t).concat([o[e]],o.slice(t,e),o.slice(e+1)),this.replace(r)}},t.prototype.toString=function(){return"[mobx.array] "+Array.prototype.toString.apply(this.$mobx.values,arguments)},t.prototype.toLocaleString=function(){return"[mobx.array] "+Array.prototype.toLocaleString.apply(this.$mobx.values,arguments)},t}(on);vt(an.prototype,function(){return dt(this.slice())}),kt(an.prototype,["constructor","intercept","observe","clear","concat","replace","toJS","toJSON","peek","find","splice","push","pop","shift","unshift","reverse","sort","remove","move","toString","toLocaleString"]),Object.defineProperty(an.prototype,"length",{enumerable:!1,configurable:!0,get:function(){return this.$mobx.getArrayLength()},set:function(e){this.$mobx.setArrayLength(e)}}),["every","filter","forEach","indexOf","join","lastIndexOf","map","reduce","reduceRight","slice","some"].forEach(function(e){var t=Array.prototype[e];yt("function"==typeof t,"Base function not defined on Array prototype: '"+e+"'"),It(an.prototype,e,function(){return this.$mobx.atom.reportObserved(),t.apply(this.$mobx.values,arguments)})});var un={configurable:!0,enumerable:!1,set:Ge(0),get:Ke(0)};We(1e3),exports.fastArray=Xe;var cn=Pt("ObservableArrayAdministration",sn);exports.isObservableArray=Ye;var ln={},pn=function(){function e(e,t){var n=this;this.$mobx=ln,this._data={},this._hasMap={},this.name="ObservableMap@"+bt(),this._keys=new an(null,tn.Reference,this.name+".keys()",(!0)),this.interceptors=null,this.changeListeners=null,this._valueMode=Ne(t),this._valueMode===tn.Flat&&(this._valueMode=tn.Reference),N(!0,function(){St(e)?n.merge(e):Array.isArray(e)&&e.forEach(function(e){var t=e[0],r=e[1];return n.set(t,r)})})}return e.prototype._has=function(e){return"undefined"!=typeof this._data[e]},e.prototype.has=function(e){return!!this.isValidKey(e)&&(e=""+e,this._hasMap[e]?this._hasMap[e].get():this._updateHasMapEntry(e,!1).get())},e.prototype.set=function(e,t){this.assertValidKey(e),e=""+e;var n=this._has(e);if(Fe(t,"[mobx.map.set] Expected unwrapped value to be inserted to key '"+e+"'. If you need to use modifiers pass them as second argument to the constructor"),ke(this)){var r=Te(this,{type:n?"update":"add",object:this,newValue:t,name:e});if(!r)return;t=r.newValue}n?this._updateValue(e,t):this._addValue(e,t)},e.prototype.delete=function(e){var t=this;if(this.assertValidKey(e),e=""+e,ke(this)){var n=Te(this,{type:"delete",object:this,name:e});if(!n)return!1}if(this._has(e)){var r=me(),o=je(this),n=o||r?{type:"delete",object:this,oldValue:this._data[e].value,name:e}:null;return r&&xe(n),Oe(function(){t._keys.remove(e),t._updateHasMapEntry(e,!1);var n=t._data[e];n.setNewValue(void 0),t._data[e]=void 0},void 0,!1),o&&Le(this,n),r&&we(),!0}return!1},e.prototype._updateHasMapEntry=function(e,t){var n=this._hasMap[e];return n?n.setNewValue(t):n=this._hasMap[e]=new mn(t,tn.Reference,this.name+"."+e+"?",(!1)),n},e.prototype._updateValue=function(e,t){var n=this._data[e];if(t=n.prepareNewValue(t),t!==yn){var r=me(),o=je(this),i=o||r?{type:"update",object:this,oldValue:n.value,name:e,newValue:t}:null;r&&xe(i),n.setNewValue(t),o&&Le(this,i),r&&we()}},e.prototype._addValue=function(e,t){var n=this;Oe(function(){var r=n._data[e]=new mn(t,n._valueMode,n.name+"."+e,(!1));t=r.value,n._updateHasMapEntry(e,!0),n._keys.push(e)},void 0,!1);var r=me(),o=je(this),i=o||r?{type:"add",object:this,name:e,newValue:t}:null;r&&xe(i),o&&Le(this,i),r&&we()},e.prototype.get=function(e){if(e=""+e,this.has(e))return this._data[e].get()},e.prototype.keys=function(){return dt(this._keys.slice())},e.prototype.values=function(){return dt(this._keys.map(this.get,this))},e.prototype.entries=function(){var e=this;return dt(this._keys.map(function(t){return[t,e.get(t)]}))},e.prototype.forEach=function(e,t){var n=this;this.keys().forEach(function(r){return e.call(t,n.get(r),r)})},e.prototype.merge=function(e){var t=this;return Oe(function(){fn(e)?e.keys().forEach(function(n){return t.set(n,e.get(n))}):Object.keys(e).forEach(function(n){return t.set(n,e[n])})},void 0,!1),this},e.prototype.clear=function(){var e=this;Oe(function(){Y(function(){e.keys().forEach(e.delete,e)})},void 0,!1)},Object.defineProperty(e.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),e.prototype.toJS=function(){var e=this,t={};return this.keys().forEach(function(n){return t[n]=e.get(n)}),t},e.prototype.toJs=function(){return mt("toJs is deprecated, use toJS instead"),this.toJS()},e.prototype.toJSON=function(){return this.toJS()},e.prototype.isValidKey=function(e){return null!==e&&void 0!==e&&("string"==typeof e||"number"==typeof e||"boolean"==typeof e)},e.prototype.assertValidKey=function(e){if(!this.isValidKey(e))throw new Error("[mobx.map] Invalid key: '"+e+"'")},e.prototype.toString=function(){var e=this;return this.name+"[{ "+this.keys().map(function(t){return t+": "+e.get(t)}).join(", ")+" }]"},e.prototype.observe=function(e,t){return yt(t!==!0,"`observe` doesn't support the fire immediately property for observable maps."),Ee(this,e)},e.prototype.intercept=function(e){return Ie(this,e)},e}();exports.ObservableMap=pn,vt(pn.prototype,function(){return this.entries()}),exports.map=qe;var fn=Pt("ObservableMap",pn);exports.isObservableMap=fn;var hn=function(){function e(e,t,n){this.target=e,this.name=t,this.mode=n,this.values={},this.changeListeners=null,this.interceptors=null}return e.prototype.observe=function(e,t){return yt(t!==!0,"`observe` doesn't support the fire immediately property for observable objects."),Ee(this,e)},e.prototype.intercept=function(e){return Ie(this,e)},e}(),dn={},vn={},bn=Pt("ObservableObjectAdministration",hn);exports.isObservableObject=it;var yn={},mn=function(e){function t(t,n,r,o){void 0===r&&(r="ObservableValue@"+bt()),void 0===o&&(o=!0),e.call(this,r),this.mode=n,this.hasUnreportedChange=!1,this.value=void 0;var i=Ue(t,tn.Recursive),s=i[0],a=i[1];this.mode===tn.Recursive&&(this.mode=s),this.value=ze(a,this.mode,this.name),o&&me()&&ge({type:"create",object:this,newValue:this.value})}return Vt(t,e),t.prototype.set=function(e){var t=this.value;if(e=this.prepareNewValue(e),e!==yn){var n=me();n&&xe({type:"update",object:this,newValue:e,oldValue:t}),this.setNewValue(e),n&&we()}},t.prototype.prepareNewValue=function(e){if(Fe(e,"Modifiers cannot be used on non-initial values."),G(),ke(this)){var t=Te(this,{object:this,type:"update",newValue:e});if(!t)return yn;e=t.newValue}var n=At(this.mode===tn.Structure,this.value,e);return n?ze(e,this.mode,this.name):yn},t.prototype.setNewValue=function(e){var t=this.value;this.value=e,this.reportChanged(),je(this)&&Le(this,[e,t])},t.prototype.get=function(){return this.reportObserved(),this.value},t.prototype.intercept=function(e){return Ie(this,e)},t.prototype.observe=function(e,t){return t&&e(this.value,void 0),Ee(this,e)},t.prototype.toJSON=function(){return this.get()},t.prototype.toString=function(){return this.name+"["+this.value+"]"},t}(Bt),gn=Pt("ObservableValue",mn),xn="__$$iterating",wn=function(){function e(){this.listeners=[],mt("extras.SimpleEventEmitter is deprecated and will be removed in the next major release")}return e.prototype.emit=function(){for(var e=this.listeners.slice(),t=0,n=e.length;t<n;t++)e[t].apply(null,arguments)},e.prototype.on=function(e){var t=this;return this.listeners.push(e),gt(function(){var n=t.listeners.indexOf(e);n!==-1&&t.listeners.splice(n,1)})},e.prototype.once=function(e){var t=this.on(function(){t(),e.apply(this,arguments)});return t},e}();exports.SimpleEventEmitter=wn;var _n=[];Object.freeze(_n);var Sn=[],On=function(){},An=Object.prototype.hasOwnProperty;exports.isArrayLike=Dt; //# sourceMappingURL=lib/mobx.min.js.map
src/components/PreviousMeetupsList.js
teamstrobe/mancreact-client
import React from 'react'; import { Link } from 'react-router-dom'; import { groupBy } from 'lodash'; import moment from 'moment'; const PreviousMeetupsList = ({ events }) => { const eventsByYear = groupBy(events, event => moment(event.time).format('YYYY')); const sortedYears = Object.keys(eventsByYear).sort().reverse(); return ( <section> <h2 className="label prev-list-title">Previous meetups</h2> <div className="prev-list-group"> {sortedYears.map(year => { const events = eventsByYear[year]; return ( <div key={year} className="prev-list-group__item"> <h3>{year}</h3> <ul className="prev-list"> {events.map(event => { const month = moment(event.time).format('MMMM'); return ( <li key={event.id}> <Link to={`/events/${event.id}`}> {month} </Link> </li> ); })} </ul> </div> ); })} </div> </section> ); }; export default PreviousMeetupsList;
common/views/Dashboard/Dashboard.js
sauleddy/HomePortal
import React, { Component } from 'react'; import { Bar, Line } from 'react-chartjs-2'; import { Dropdown, DropdownMenu, DropdownItem, Progress } from 'reactstrap'; const brandPrimary = '#20a8d8'; const brandSuccess = '#4dbd74'; const brandInfo = '#63c2de'; const brandDanger = '#f86c6b'; // Card Chart 1 const cardChartData1 = { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'My First dataset', backgroundColor: brandPrimary, borderColor: 'rgba(255,255,255,.55)', data: [65, 59, 84, 84, 51, 55, 40] } ], }; const cardChartOpts1 = { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ gridLines: { color: 'transparent', zeroLineColor: 'transparent' }, ticks: { fontSize: 2, fontColor: 'transparent', } }], yAxes: [{ display: false, ticks: { display: false, min: Math.min.apply(Math, cardChartData1.datasets[0].data) - 5, max: Math.max.apply(Math, cardChartData1.datasets[0].data) + 5, } }], }, elements: { line: { borderWidth: 1 }, point: { radius: 4, hitRadius: 10, hoverRadius: 4, }, } } // Card Chart 2 const cardChartData2 = { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'My First dataset', backgroundColor: brandInfo, borderColor: 'rgba(255,255,255,.55)', data: [1, 18, 9, 17, 34, 22, 11] } ], }; const cardChartOpts2 = { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ gridLines: { color: 'transparent', zeroLineColor: 'transparent' }, ticks: { fontSize: 2, fontColor: 'transparent', } }], yAxes: [{ display: false, ticks: { display: false, min: Math.min.apply(Math, cardChartData2.datasets[0].data) - 5, max: Math.max.apply(Math, cardChartData2.datasets[0].data) + 5, } }], }, elements: { line: { tension: 0.00001, borderWidth: 1 }, point: { radius: 4, hitRadius: 10, hoverRadius: 4, }, } } // Card Chart 3 const cardChartData3 = { labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'], datasets: [ { label: 'My First dataset', backgroundColor: 'rgba(255,255,255,.2)', borderColor: 'rgba(255,255,255,.55)', data: [78, 81, 80, 45, 34, 12, 40] } ], }; const cardChartOpts3 = { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ display: false }], yAxes: [{ display: false }], }, elements: { line: { borderWidth: 2 }, point: { radius: 0, hitRadius: 10, hoverRadius: 4, }, } } // Card Chart 4 const cardChartData4 = { labels: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''], datasets: [ { label: 'My First dataset', backgroundColor: 'rgba(255,255,255,.3)', borderColor: 'transparent', data: [78, 81, 80, 45, 34, 12, 40, 75, 34, 89, 32, 68, 54, 72, 18, 98] } ], }; const cardChartOpts4 = { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ display: false, barPercentage: 0.6, }], yAxes: [{ display: false, }] } } // Main Chart // convert Hex to RGBA function convertHex(hex,opacity) { hex = hex.replace('#',''); var r = parseInt(hex.substring(0,2), 16); var g = parseInt(hex.substring(2,4), 16); var b = parseInt(hex.substring(4,6), 16); var result = 'rgba('+r+','+g+','+b+','+opacity/100+')'; return result; } //Random Numbers function random(min,max) { return Math.floor(Math.random()*(max-min+1)+min); } var elements = 27; var data1 = []; var data2 = []; var data3 = []; for (var i = 0; i <= elements; i++) { data1.push(random(50,200)); data2.push(random(80,100)); data3.push(65); } const mainChart = { labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S', 'M', 'T', 'W', 'T', 'F', 'S', 'S', 'M', 'T', 'W', 'T', 'F', 'S', 'S', 'M', 'T', 'W', 'T', 'F', 'S', 'S'], datasets: [ { label: 'My First dataset', backgroundColor: convertHex(brandInfo,10), borderColor: brandInfo, pointHoverBackgroundColor: '#fff', borderWidth: 2, data: data1 }, { label: 'My Second dataset', backgroundColor: 'transparent', borderColor: brandSuccess, pointHoverBackgroundColor: '#fff', borderWidth: 2, data: data2 }, { label: 'My Third dataset', backgroundColor: 'transparent', borderColor: brandDanger, pointHoverBackgroundColor: '#fff', borderWidth: 1, borderDash: [8, 5], data: data3 } ] } const mainChartOpts = { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ gridLines: { drawOnChartArea: false, } }], yAxes: [{ ticks: { beginAtZero: true, maxTicksLimit: 5, stepSize: Math.ceil(250 / 5), max: 250 } }] }, elements: { point: { radius: 0, hitRadius: 10, hoverRadius: 4, hoverBorderWidth: 3, } } } class Dashboard extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { dropdownOpen: false }; } toggle() { this.setState({ dropdownOpen: !this.state.dropdownOpen }); } render() { return ( <div className="animated fadeIn"> <div className="row"> <div className="col-sm-6 col-lg-3"> <div className="card card-inverse card-primary"> <div className="card-block pb-0"> <div className="btn-group float-right"> <Dropdown isOpen={this.state.card1} toggle={() => { this.setState({ card1: !this.state.card1 }); }}> <button onClick={() => { this.setState({ card1: !this.state.card1 }); }} className="btn btn-transparent active dropdown-toggle p-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded={this.state.card1}> <i className="icon-settings"></i> </button> <DropdownMenu> <DropdownItem>Action</DropdownItem> <DropdownItem>Another action</DropdownItem> <DropdownItem>Something else here</DropdownItem> </DropdownMenu> </Dropdown> </div> <h4 className="mb-0">9.823</h4> <p>Members online</p> </div> <div className="chart-wrapper px-3"> <Line data={cardChartData1} options={cardChartOpts1} height={70}/> </div> </div> </div> <div className="col-sm-6 col-lg-3"> <div className="card card-inverse card-info"> <div className="card-block pb-0"> <div className="btn-group float-right"> <Dropdown isOpen={this.state.card2} toggle={() => { this.setState({ card2: !this.state.card2 }); }}> <button onClick={() => { this.setState({ card2: !this.state.card2 }); }} className="btn btn-transparent active dropdown-toggle p-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded={this.state.card2}> <i className="icon-settings"></i> </button> <DropdownMenu> <DropdownItem>Action</DropdownItem> <DropdownItem>Another action</DropdownItem> <DropdownItem>Something else here</DropdownItem> </DropdownMenu> </Dropdown> </div> <h4 className="mb-0">9.823</h4> <p>Members online</p> </div> <div className="chart-wrapper px-3"> <Line data={cardChartData2} options={cardChartOpts2} height={70}/> </div> </div> </div> <div className="col-sm-6 col-lg-3"> <div className="card card-inverse card-warning"> <div className="card-block pb-0"> <div className="btn-group float-right"> <Dropdown isOpen={this.state.card3} toggle={() => { this.setState({ card3: !this.state.card3 }); }}> <button onClick={() => { this.setState({ card3: !this.state.card3 }); }} className="btn btn-transparent active dropdown-toggle p-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded={this.state.card3}> <i className="icon-settings"></i> </button> <DropdownMenu> <DropdownItem>Action</DropdownItem> <DropdownItem>Another action</DropdownItem> <DropdownItem>Something else here</DropdownItem> </DropdownMenu> </Dropdown> </div> <h4 className="mb-0">9.823</h4> <p>Members online</p> </div> <div className="chart-wrapper"> <Line data={cardChartData3} options={cardChartOpts3} height={70}/> </div> </div> </div> <div className="col-sm-6 col-lg-3"> <div className="card card-inverse card-danger"> <div className="card-block pb-0"> <div className="btn-group float-right"> <Dropdown isOpen={this.state.card4} toggle={() => { this.setState({ card4: !this.state.card4 }); }}> <button onClick={() => { this.setState({ card4: !this.state.card4 }); }} className="btn btn-transparent active dropdown-toggle p-0" data-toggle="dropdown" aria-haspopup="true" aria-expanded={this.state.card4}> <i className="icon-settings"></i> </button> <DropdownMenu> <DropdownItem>Action</DropdownItem> <DropdownItem>Another action</DropdownItem> <DropdownItem>Something else here</DropdownItem> </DropdownMenu> </Dropdown> </div> <h4 className="mb-0">9.823</h4> <p>Members online</p> </div> <div className="chart-wrapper px-3"> <Bar data={cardChartData4} options={cardChartOpts4} height={70}/> </div> </div> </div> </div> <div className="card"> <div className="card-block"> <div className="row"> <div className="col-sm-5"> <h4 className="card-title mb-0">Traffic</h4> <div className="small text-muted">November 2015</div> </div> <div className="col-sm-7 hidden-sm-down"> <button type="button" className="btn btn-primary float-right"><i className="icon-cloud-download"></i></button> <div className="btn-toolbar float-right" role="toolbar" aria-label="Toolbar with button groups"> <div className="btn-group mr-3" data-toggle="buttons" aria-label="First group"> <label className="btn btn-outline-secondary"> <input type="radio" name="options" id="option1"/> Day </label> <label className="btn btn-outline-secondary active"> <input type="radio" name="options" id="option2" defaultChecked/> Month </label> <label className="btn btn-outline-secondary"> <input type="radio" name="options" id="option3"/> Year </label> </div> </div> </div> </div> <div className="chart-wrapper" style={{height: 300 + 'px', marginTop: 40 + 'px'}}> <Line data={mainChart} options={mainChartOpts} height={300}/> </div> </div> <div className="card-footer"> <ul> <li> <div className="text-muted">Visits</div> <strong>29.703 Users (40%)</strong> <Progress className="progress-xs mt-2" color="success" value="40" /> </li> <li className="hidden-sm-down"> <div className="text-muted">Unique</div> <strong>24.093 Users (20%)</strong> <Progress className="progress-xs mt-2" color="info" value="20" /> </li> <li> <div className="text-muted">Pageviews</div> <strong>78.706 Views (60%)</strong> <Progress className="progress-xs mt-2" color="warning" value="60" /> </li> <li className="hidden-sm-down"> <div className="text-muted">New Users</div> <strong>22.123 Users (80%)</strong> <Progress className="progress-xs mt-2" color="danger" value="80" /> </li> <li className="hidden-sm-down"> <div className="text-muted">Bounce Rate</div> <strong>40.15%</strong> <Progress className="progress-xs mt-2" color="primary" value="40" /> </li> </ul> </div> </div> <div className="row"> <div className="col-sm-6 col-lg-3"> <div className="social-box facebook"> <i className="fa fa-facebook"></i> <div className="chart-wrapper"> <canvas id="social-box-chart-1" height="90"></canvas> </div> <ul> <li> <strong>89k</strong> <span>friends</span> </li> <li> <strong>459</strong> <span>feeds</span> </li> </ul> </div> </div> <div className="col-sm-6 col-lg-3"> <div className="social-box twitter"> <i className="fa fa-twitter"></i> <div className="chart-wrapper"> <canvas id="social-box-chart-2" height="90"></canvas> </div> <ul> <li> <strong>973k</strong> <span>followers</span> </li> <li> <strong>1.792</strong> <span>tweets</span> </li> </ul> </div> </div> <div className="col-sm-6 col-lg-3"> <div className="social-box linkedin"> <i className="fa fa-linkedin"></i> <div className="chart-wrapper"> <canvas id="social-box-chart-3" height="90"></canvas> </div> <ul> <li> <strong>500+</strong> <span>contacts</span> </li> <li> <strong>292</strong> <span>feeds</span> </li> </ul> </div> </div> <div className="col-sm-6 col-lg-3"> <div className="social-box google-plus"> <i className="fa fa-google-plus"></i> <div className="chart-wrapper"> <canvas id="social-box-chart-4" height="90"></canvas> </div> <ul> <li> <strong>894</strong> <span>followers</span> </li> <li> <strong>92</strong> <span>circles</span> </li> </ul> </div> </div> </div> <div className="row"> <div className="col-md-12"> <div className="card"> <div className="card-header"> Traffic &amp; Sales </div> <div className="card-block"> <div className="row"> <div className="col-sm-12 col-lg-4"> <div className="row"> <div className="col-sm-6"> <div className="callout callout-info"> <small className="text-muted">New Clients</small><br/> <strong className="h4">9,123</strong> <div className="chart-wrapper"> <canvas id="sparkline-chart-1" width="100" height="30"></canvas> </div> </div> </div> <div className="col-sm-6"> <div className="callout callout-danger"> <small className="text-muted">Recuring Clients</small><br/> <strong className="h4">22,643</strong> <div className="chart-wrapper"> <canvas id="sparkline-chart-2" width="100" height="30"></canvas> </div> </div> </div> </div> <hr className="mt-0"/> <ul className="horizontal-bars"> <li> <div className="title"> Monday </div> <div className="bars"> <Progress className="progress-xs" color="info" value="34" /> <Progress className="progress-xs" color="danger" value="78" /> </div> </li> <li> <div className="title"> Tuesday </div> <div className="bars"> <Progress className="progress-xs" color="info" value="56" /> <Progress className="progress-xs" color="danger" value="94" /> </div> </li> <li> <div className="title"> Wednesday </div> <div className="bars"> <Progress className="progress-xs" color="info" value="12" /> <Progress className="progress-xs" color="danger" value="67" /> </div> </li> <li> <div className="title"> Thursday </div> <div className="bars"> <Progress className="progress-xs" color="info" value="43" /> <Progress className="progress-xs" color="danger" value="91" /> </div> </li> <li> <div className="title"> Friday </div> <div className="bars"> <Progress className="progress-xs" color="info" value="22" /> <Progress className="progress-xs" color="danger" value="73" /> </div> </li> <li> <div className="title"> Saturday </div> <div className="bars"> <Progress className="progress-xs" color="info" value="53" /> <Progress className="progress-xs" color="danger" value="82" /> </div> </li> <li> <div className="title"> Sunday </div> <div className="bars"> <Progress className="progress-xs" color="info" value="9" /> <Progress className="progress-xs" color="danger" value="69" /> </div> </li> <li className="legend"> <span className="badge badge-pill badge-info"></span> <small>New clients</small> &nbsp; <span className="badge badge-pill badge-danger"></span> <small>Recurring clients</small> </li> </ul> </div> <div className="col-sm-6 col-lg-4"> <div className="row"> <div className="col-sm-6"> <div className="callout callout-warning"> <small className="text-muted">Pageviews</small><br/> <strong className="h4">78,623</strong> <div className="chart-wrapper"> <canvas id="sparkline-chart-3" width="100" height="30"></canvas> </div> </div> </div> <div className="col-sm-6"> <div className="callout callout-success"> <small className="text-muted">Organic</small><br/> <strong className="h4">49,123</strong> <div className="chart-wrapper"> <canvas id="sparkline-chart-4" width="100" height="30"></canvas> </div> </div> </div> </div> <hr className="mt-0"/> <ul className="horizontal-bars type-2"> <li> <i className="icon-user"></i> <span className="title">Male</span> <span className="value">43%</span> <div className="bars"> <Progress className="progress-xs" color="warning" value="43" /> </div> </li> <li> <i className="icon-user-female"></i> <span className="title">Female</span> <span className="value">37%</span> <div className="bars"> <Progress className="progress-xs" color="warning" value="37" /> </div> </li> <li className="divider"></li> <li> <i className="icon-globe"></i> <span className="title">Organic Search</span> <span className="value">191,235 <span className="text-muted small">(56%)</span></span> <div className="bars"> <Progress className="progress-xs" color="success" value="56" /> </div> </li> <li> <i className="icon-social-facebook"></i> <span className="title">Facebook</span> <span className="value">51,223 <span className="text-muted small">(15%)</span></span> <div className="bars"> <Progress className="progress-xs" color="success" value="15" /> </div> </li> <li> <i className="icon-social-twitter"></i> <span className="title">Twitter</span> <span className="value">37,564 <span className="text-muted small">(11%)</span></span> <div className="bars"> <Progress className="progress-xs" color="success" value="11" /> </div> </li> <li> <i className="icon-social-linkedin"></i> <span className="title">LinkedIn</span> <span className="value">27,319 <span className="text-muted small">(8%)</span></span> <div className="bars"> <Progress className="progress-xs" color="success" value="8" /> </div> </li> <li className="divider text-center"> <button type="button" className="btn btn-sm btn-link text-muted" data-toggle="tooltip" data-placement="top" title="" data-original-title="show more"><i className="icon-options"></i></button> </li> </ul> </div> <div className="col-sm-6 col-lg-4"> <div className="row"> <div className="col-sm-6"> <div className="callout"> <small className="text-muted">CTR</small><br/> <strong className="h4">23%</strong> <div className="chart-wrapper"> <canvas id="sparkline-chart-5" width="100" height="30"></canvas> </div> </div> </div> <div className="col-sm-6"> <div className="callout callout-primary"> <small className="text-muted">Bounce Rate</small><br/> <strong className="h4">5%</strong> <div className="chart-wrapper"> <canvas id="sparkline-chart-6" width="100" height="30"></canvas> </div> </div> </div> </div> <hr className="mt-0"/> <ul className="icons-list"> <li> <i className="icon-screen-desktop bg-primary"></i> <div className="desc"> <div className="title">iMac 4k</div> <small>Lorem ipsum dolor sit amet</small> </div> <div className="value"> <div className="small text-muted">Sold this week</div> <strong>1.924</strong> </div> <div className="actions"> <button type="button" className="btn btn-link text-muted"><i className="icon-settings"></i></button> </div> </li> <li> <i className="icon-screen-smartphone bg-info"></i> <div className="desc"> <div className="title">Samsung Galaxy Edge</div> <small>Lorem ipsum dolor sit amet</small> </div> <div className="value"> <div className="small text-muted">Sold this week</div> <strong>1.224</strong> </div> <div className="actions"> <button type="button" className="btn btn-link text-muted"><i className="icon-settings"></i></button> </div> </li> <li> <i className="icon-screen-smartphone bg-warning"></i> <div className="desc"> <div className="title">iPhone 6S</div> <small>Lorem ipsum dolor sit amet</small> </div> <div className="value"> <div className="small text-muted">Sold this week</div> <strong>1.163</strong> </div> <div className="actions"> <button type="button" className="btn btn-link text-muted"><i className="icon-settings"></i></button> </div> </li> <li> <i className="icon-user bg-danger"></i> <div className="desc"> <div className="title">Premium accounts</div> <small>Lorem ipsum dolor sit amet</small> </div> <div className="value"> <div className="small text-muted">Sold this week</div> <strong>928</strong> </div> <div className="actions"> <button type="button" className="btn btn-link text-muted"><i className="icon-settings"></i></button> </div> </li> <li> <i className="icon-social-spotify bg-success"></i> <div className="desc"> <div className="title">Spotify Subscriptions</div> <small>Lorem ipsum dolor sit amet</small> </div> <div className="value"> <div className="small text-muted">Sold this week</div> <strong>893</strong> </div> <div className="actions"> <button type="button" className="btn btn-link text-muted"><i className="icon-settings"></i></button> </div> </li> <li> <i className="icon-cloud-download bg-danger"></i> <div className="desc"> <div className="title">Ebook</div> <small>Lorem ipsum dolor sit amet</small> </div> <div className="value"> <div className="small text-muted">Downloads</div> <strong>121.924</strong> </div> <div className="actions"> <button type="button" className="btn btn-link text-muted"><i className="icon-settings"></i></button> </div> </li> <li> <i className="icon-camera bg-warning"></i> <div className="desc"> <div className="title">Photos</div> <small>Lorem ipsum dolor sit amet</small> </div> <div className="value"> <div className="small text-muted">Uploaded</div> <strong>12.125</strong> </div> <div className="actions"> <button type="button" className="btn btn-link text-muted"><i className="icon-settings"></i></button> </div> </li> <li className="divider text-center"> <button type="button" className="btn btn-sm btn-link text-muted" data-toggle="tooltip" data-placement="top" title="show more"><i className="icon-options"></i></button> </li> </ul> </div> </div> <br/> <table className="table table-hover table-outline mb-0 hidden-sm-down"> <thead className="thead-default"> <tr> <th className="text-center"><i className="icon-people"></i></th> <th>User</th> <th className="text-center">Country</th> <th>Usage</th> <th className="text-center">Payment Method</th> <th>Activity</th> </tr> </thead> <tbody> <tr> <td className="text-center"> <div className="avatar"> <img src={'img/avatars/1.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> <span className="avatar-status badge-success"></span> </div> </td> <td> <div>Yiorgos Avraamu</div> <div className="small text-muted"> <span>New</span> | Registered: Jan 1, 2015 </div> </td> <td className="text-center"> <img src={'img/flags/USA.png'} alt="USA" style={{height: 24 + 'px'}}/> </td> <td> <div className="clearfix"> <div className="float-left"> <strong>50%</strong> </div> <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> </div> <Progress className="progress-xs" color="success" value="50" /> </td> <td className="text-center"> <i className="fa fa-cc-mastercard" style={{fontSize: 24 + 'px'}}></i> </td> <td> <div className="small text-muted">Last login</div> <strong>10 sec ago</strong> </td> </tr> <tr> <td className="text-center"> <div className="avatar"> <img src={'img/avatars/2.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> <span className="avatar-status badge-danger"></span> </div> </td> <td> <div>Avram Tarasios</div> <div className="small text-muted"> <span>Recurring</span> | Registered: Jan 1, 2015 </div> </td> <td className="text-center"> <img src={'img/flags/Brazil.png'} alt="Brazil" style={{height: 24 + 'px'}}/> </td> <td> <div className="clearfix"> <div className="float-left"> <strong>10%</strong> </div> <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> </div> <Progress className="progress-xs" color="info" value="10" /> </td> <td className="text-center"> <i className="fa fa-cc-visa" style={{fontSize: 24 + 'px'}}></i> </td> <td> <div className="small text-muted">Last login</div> <strong>5 minutes ago</strong> </td> </tr> <tr> <td className="text-center"> <div className="avatar"> <img src={'img/avatars/3.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> <span className="avatar-status badge-warning"></span> </div> </td> <td> <div>Quintin Ed</div> <div className="small text-muted"> <span>New</span> | Registered: Jan 1, 2015 </div> </td> <td className="text-center"> <img src={'img/flags/India.png'} alt="India" style={{height: 24 + 'px'}}/> </td> <td> <div className="clearfix"> <div className="float-left"> <strong>74%</strong> </div> <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> </div> <Progress className="progress-xs" color="warning" value="74" /> </td> <td className="text-center"> <i className="fa fa-cc-stripe" style={{fontSize: 24 + 'px'}}></i> </td> <td> <div className="small text-muted">Last login</div> <strong>1 hour ago</strong> </td> </tr> <tr> <td className="text-center"> <div className="avatar"> <img src={'img/avatars/4.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> <span className="avatar-status badge-default"></span> </div> </td> <td> <div>Enéas Kwadwo</div> <div className="small text-muted"> <span>New</span> | Registered: Jan 1, 2015 </div> </td> <td className="text-center"> <img src={'img/flags/France.png'} alt="France" style={{height: 24 + 'px'}}/> </td> <td> <div className="clearfix"> <div className="float-left"> <strong>98%</strong> </div> <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> </div> <Progress className="progress-xs" color="danger" value="98" /> </td> <td className="text-center"> <i className="fa fa-paypal" style={{fontSize: 24 + 'px'}}></i> </td> <td> <div className="small text-muted">Last login</div> <strong>Last month</strong> </td> </tr> <tr> <td className="text-center"> <div className="avatar"> <img src={'img/avatars/5.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> <span className="avatar-status badge-success"></span> </div> </td> <td> <div>Agapetus Tadeáš</div> <div className="small text-muted"> <span>New</span> | Registered: Jan 1, 2015 </div> </td> <td className="text-center"> <img src={'img/flags/Spain.png'} alt="Spain" style={{height: 24 + 'px'}}/> </td> <td> <div className="clearfix"> <div className="float-left"> <strong>22%</strong> </div> <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> </div> <Progress className="progress-xs" color="info" value="22" /> </td> <td className="text-center"> <i className="fa fa-google-wallet" style={{fontSize: 24 + 'px'}}></i> </td> <td> <div className="small text-muted">Last login</div> <strong>Last week</strong> </td> </tr> <tr> <td className="text-center"> <div className="avatar"> <img src={'img/avatars/6.jpg'} className="img-avatar" alt="admin@bootstrapmaster.com"/> <span className="avatar-status badge-danger"></span> </div> </td> <td> <div>Friderik Dávid</div> <div className="small text-muted"> <span>New</span> | Registered: Jan 1, 2015 </div> </td> <td className="text-center"> <img src={'img/flags/Poland.png'} alt="Poland" style={{height: 24 + 'px'}}/> </td> <td> <div className="clearfix"> <div className="float-left"> <strong>43%</strong> </div> <div className="float-right"> <small className="text-muted">Jun 11, 2015 - Jul 10, 2015</small> </div> </div> <Progress className="progress-xs" color="success" value="43" /> </td> <td className="text-center"> <i className="fa fa-cc-amex" style={{fontSize: 24 + 'px'}}></i> </td> <td> <div className="small text-muted">Last login</div> <strong>Yesterday</strong> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> ) } } export default Dashboard;
Firebase/node_modules/firebase-admin/node_modules/firebase/firebase-react-native.js
CodePath-Parse/MiAR
/*! @license Firebase v3.9.0 Build: rev-cc77c9e Terms: https://firebase.google.com/terms/ */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var firebase = require('./app'); require('./auth'); var Storage, XMLHttpRequest; require('./database'); require('./storage'); var AsyncStorage = require('react-native').AsyncStorage; firebase.INTERNAL.extendNamespace({ 'INTERNAL': { 'reactNative': { 'AsyncStorage': AsyncStorage } } }); exports.default = firebase; module.exports = exports['default']; //# sourceMappingURL=firebase.js.map
packages/material-ui-icons/src/SignalWifi3BarTwoTone.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5 23.64 7z" /><path d="M3.53 10.95L12 21.5l8.47-10.55C20.04 10.62 16.81 8 12 8s-8.04 2.62-8.47 2.95z" /></React.Fragment> , 'SignalWifi3BarTwoTone');
src/pages/Profile.js
michaelfriedman/capstone-g40
import React, { Component } from 'react'; import axios from 'axios'; import Moment from 'react-moment'; import { Image, Panel, Col, Well, Modal, Button, Glyphicon, Collapse } from 'react-bootstrap'; import GoogleMap from '../features/map/GoogleMap'; class Profile extends Component { constructor(props) { super(props); this.state = { name: '', profileUrl: '', joinedOn: '', email: '', userId: '', phone: '', list: '', review_body: [], events: [], organized_events: [], eventObjArr: [], showModal: false, showContact: false, showEvents: false, }; this.open = this.open.bind(this); this.close = this.close.bind(this); this.openContact = this.openContact.bind(this); this.closeContact = this.closeContact.bind(this); this.openEvents = this.openEvents.bind(this); this.closeEvents = this.closeEvents.bind(this); } componentDidMount() { axios.get('/users/id') .then(res => { const name = `${res.data.first_name} ${res.data.last_name}`; const email = res.data.email; const area = res.data.area; const phone = res.data.phone; const profileUrl = res.data.profile_photo_url; const joinedOn = res.data.created_at.slice(0, 10); const userId = res.data.id; this.setState({ name, profileUrl, joinedOn, email, userId, area, phone }); axios.get(`/reviews/user/${this.state.userId}`) .then(res => { this.setState({ review_body: res.data, }); }); axios.get(`/users_events/user/${this.state.userId}`) .then(res => { const events = []; // eslint-disable-next-line array-callback-return res.data.map(item => { events.push(item.event_id); }); this.setState({ events }); const promises = this.state.events.map(item => axios.get(`/events/event/${item}`)); Promise.all(promises).then(res => { const eventObjArr = res.map(item => item.data[0]); this.setState({ eventObjArr, }); }); }); }); } close() { this.setState({ showModal: false }); } open() { this.setState({ showModal: true }); } openContact() { this.setState({ showContact: true }); } closeContact() { this.setState({ showContact: false }); } openEvents() { this.setState({ showEvents: true }); } closeEvents() { this.setState({ showEvents: false }); } render() { return ( <div className="container"> <Well style={{ backgroundImage: 'url(http://res.cloudinary.com/dk5dqve4y/image/upload/c_scale,h_291,q_20,w_1140/v1491267783/AdobeStock_93889805_cn6fbz.jpg)' }}> <center> <Image thumbnail responsive rounded src={this.state.profileUrl} width="150" height="150" /> <h3 style={{ color: 'white' }}>{this.state.name}</h3> </center> </Well> <div className="well" style={{ maxWidth: 400, margin: '0 auto 10px' }}> { this.state.review_body.length ? <Button block bsStyle="default" bsSize="small" onClick={this.open} > My Trail Reviews </Button> : null } <Button block bsStyle="default" bsSize="small" onClick={this.openContact} > My Contact Info </Button> { this.state.eventObjArr.length ? <Button block bsStyle="default" bsSize="small" onClick={this.openEvents} > Upcoming Adventures </Button> : null } </div> <Modal show={this.state.showModal} onHide={this.close}> <Modal.Header closeButton> <Modal.Title style={{ textAlign: 'center' }}>{`${this.state.name}'s`} Trail Reviews</Modal.Title> </Modal.Header> <Modal.Body> { this.state.review_body && this.state.review_body.map(item => <div key={item.id}> <Panel header={<strong>{item.name}</strong>} footer={<date> <small> <Moment tz="America/Los_Angeles"> {item.created_at} </Moment> </small> </date>} > <Col> <p> <em>{item.review_body}</em> </p> </Col> </Panel> </div>) } </Modal.Body> <Modal.Footer> <Button bsStyle="danger" onClick={this.close}>Close</Button> </Modal.Footer> </Modal> <Modal show={this.state.showContact} onHide={this.closeContact}> <Modal.Header closeButton> <Modal.Title style={{ textAlign: 'center' }}>{`${this.state.name}'s`} Contact Information</Modal.Title> </Modal.Header> <Modal.Body> <p><a href={'mailto:' + this.state.email}><Glyphicon glyph="envelope" /> {this.state.email}</a></p> <p> <Glyphicon glyph="phone" /> ({this.state.phone.slice(0, 3)}) {this.state.phone.slice(3, 6)} - {this.state.phone.slice(6, 10)} </p> <div style={{ display: 'flex', justifyContent: 'space-around' }}> <a href="http://facebook.com" className="btn btn-social-icon btn-facebook"><i className="fa fa-facebook" /></a> <a className="btn btn-social-icon btn-github"><i className="fa fa-github" /></a> <a className="btn btn-social-icon btn-google-plus"> <i className="fa fa-google-plus" /> </a> <a className="btn btn-social-icon btn-instagram"><i className="fa fa-instagram" /></a> <a className="btn btn-social-icon btn-linkedin"><i className="fa fa-linkedin" /></a> <a className="btn btn-social-icon btn-twitter"><i className="fa fa-twitter" /></a> </div> </Modal.Body> <Modal.Footer> <Button bsStyle="danger" onClick={this.closeContact}>Close</Button> </Modal.Footer> </Modal> <Modal show={this.state.showEvents} onHide={this.closeEvents}> <Modal.Header closeButton> <Modal.Title style={{ textAlign: 'center' }}>{this.state.name}'s Upcoming Adventures</Modal.Title> </Modal.Header> <Modal.Body> { this.state.eventObjArr.length > 0 ? this.state.eventObjArr.map(item => <Panel header={<div> <strong>{item.trail_name} </strong> <div> <small> <Moment format="MM/DD/YYYY" tz="America/Los_Angeles" > {item.event_date} </Moment> {item.event_time} </small> </div> </div>} > <div style={{ height: '300px', border: '1px solid grey' }}> <GoogleMap lat={parseFloat(item.latitude, 10)} lng={parseFloat(item.longitude, 10)} /> </div> <div style={{ display: 'flex', justifyContent: 'center' }}> <Image thumbnail src={item.profile_photo_url} style={{ height: '100px', width: '100px', marginTop: '1%' }} /> </div> <div style={{ display: 'flex', justifyContent: 'center' }}><p>{item.first_name} {item.last_name}</p></div> <p><strong>Max Participants:</strong> {item.max_participants}</p> <p><strong>Organizer:</strong> {item.first_name} {item.last_name}</p> <p><strong>Organizer Email:</strong> {item.email}</p> <p> <strong>Organizer Phone: </strong> ({item.phone.slice(0, 3)}) {item.phone.slice(3, 6)} - {item.phone.slice(6, 10)} </p> <p><strong>Region:</strong> {item.region}</p> <p><strong>Elevation Gain:</strong> {item.elevation_gain}</p> <p><strong>Coordinates:</strong> {item.latitude}, {item.longitude}</p> <p><strong>Features:</strong> {item.features.replace(/{/, '').replace(/}/, '').replace(/"/g, '').replace(/,/g, ', ')}</p> <p><strong>Highest Point:</strong> {item.highest_point}</p> { item.driving_directions && <p> <strong>Driving Directions:</strong> <div style={{ display: 'inline' }}> <Button bsSize="xsmall" onClick={() => this.setState({ openDirections: !this.state.openDirections, })} > Directions </Button> <Collapse in={this.state.openDirections}> <div> <Well> {item.driving_directions} </Well> </div> </Collapse> </div> </p> } { item.trail_description ? <p> <strong>Trail Description: </strong> <div style={{ display: 'inline' }}> <Button bsSize="xsmall" onClick={() => this.setState({ open: !this.state.open, })} > Details </Button> <Collapse in={this.state.open}> <div> <Well> {item.trail_description} </Well> </div> </Collapse> </div> </p> : null } </Panel>, ) : null } </Modal.Body> <Modal.Footer> <Button bsStyle="danger" onClick={this.closeEvents}>Close</Button> </Modal.Footer> </Modal> <style>{` @import url('https://fonts.googleapis.com/css?family=Raleway'); .btn-social{position:relative;padding-left:44px;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.btn-social :first-child{position:absolute;left:0;top:0;bottom:0;width:32px;line-height:34px;font-size:1.6em;text-align:center;border-right:1px solid rgba(0,0,0,0.2)} .btn-social.btn-lg{padding-left:61px}.btn-social.btn-lg :first-child{line-height:45px;width:45px;font-size:1.8em} .btn-social.btn-sm{padding-left:38px}.btn-social.btn-sm :first-child{line-height:28px;width:28px;font-size:1.4em} .btn-social.btn-xs{padding-left:30px}.btn-social.btn-xs :first-child{line-height:20px;width:20px;font-size:1.2em} .btn-social-icon{position:relative;padding-left:44px;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;height:34px;width:34px;padding:0}.btn-social-icon :first-child{position:absolute;left:0;top:0;bottom:0;width:32px;line-height:34px;font-size:1.6em;text-align:center;border-right:1px solid rgba(0,0,0,0.2)} .btn-social-icon.btn-lg{padding-left:61px}.btn-social-icon.btn-lg :first-child{line-height:45px;width:45px;font-size:1.8em} .btn-social-icon.btn-sm{padding-left:38px}.btn-social-icon.btn-sm :first-child{line-height:28px;width:28px;font-size:1.4em} .btn-social-icon.btn-xs{padding-left:30px}.btn-social-icon.btn-xs :first-child{line-height:20px;width:20px;font-size:1.2em} .btn-social-icon :first-child{border:none;text-align:center;width:100% !important} .btn-social-icon.btn-lg{height:45px;width:45px;padding-left:0;padding-right:0} .btn-social-icon.btn-sm{height:30px;width:30px;padding-left:0;padding-right:0} .btn-social-icon.btn-xs{height:22px;width:22px;padding-left:0;padding-right:0} .btn-facebook{color:#fff;background-color:#3b5998;border-color:rgba(0,0,0,0.2)}.btn-facebook:hover,.btn-facebook:focus,.btn-facebook:active,.btn-facebook.active,.open .dropdown-toggle.btn-facebook{color:#fff;background-color:#30487b;border-color:rgba(0,0,0,0.2)} .btn-facebook:active,.btn-facebook.active,.open .dropdown-toggle.btn-facebook{background-image:none} .btn-facebook.disabled,.btn-facebook[disabled],fieldset[disabled] .btn-facebook,.btn-facebook.disabled:hover,.btn-facebook[disabled]:hover,fieldset[disabled] .btn-facebook:hover,.btn-facebook.disabled:focus,.btn-facebook[disabled]:focus,fieldset[disabled] .btn-facebook:focus,.btn-facebook.disabled:active,.btn-facebook[disabled]:active,fieldset[disabled] .btn-facebook:active,.btn-facebook.disabled.active,.btn-facebook[disabled].active,fieldset[disabled] .btn-facebook.active{background-color:#3b5998;border-color:rgba(0,0,0,0.2)} .btn-github{color:#fff;background-color:#444;border-color:rgba(0,0,0,0.2)}.btn-github:hover,.btn-github:focus,.btn-github:active,.btn-github.active,.open .dropdown-toggle.btn-github{color:#fff;background-color:#303030;border-color:rgba(0,0,0,0.2)} .btn-github:active,.btn-github.active,.open .dropdown-toggle.btn-github{background-image:none} .btn-github.disabled,.btn-github[disabled],fieldset[disabled] .btn-github,.btn-github.disabled:hover,.btn-github[disabled]:hover,fieldset[disabled] .btn-github:hover,.btn-github.disabled:focus,.btn-github[disabled]:focus,fieldset[disabled] .btn-github:focus,.btn-github.disabled:active,.btn-github[disabled]:active,fieldset[disabled] .btn-github:active,.btn-github.disabled.active,.btn-github[disabled].active,fieldset[disabled] .btn-github.active{background-color:#444;border-color:rgba(0,0,0,0.2)} .btn-google-plus{color:#fff;background-color:#dd4b39;border-color:rgba(0,0,0,0.2)}.btn-google-plus:hover,.btn-google-plus:focus,.btn-google-plus:active,.btn-google-plus.active,.open .dropdown-toggle.btn-google-plus{color:#fff;background-color:#ca3523;border-color:rgba(0,0,0,0.2)} .btn-google-plus:active,.btn-google-plus.active,.open .dropdown-toggle.btn-google-plus{background-image:none} .btn-google-plus.disabled,.btn-google-plus[disabled],fieldset[disabled] .btn-google-plus,.btn-google-plus.disabled:hover,.btn-google-plus[disabled]:hover,fieldset[disabled] .btn-google-plus:hover,.btn-google-plus.disabled:focus,.btn-google-plus[disabled]:focus,fieldset[disabled] .btn-google-plus:focus,.btn-google-plus.disabled:active,.btn-google-plus[disabled]:active,fieldset[disabled] .btn-google-plus:active,.btn-google-plus.disabled.active,.btn-google-plus[disabled].active,fieldset[disabled] .btn-google-plus.active{background-color:#dd4b39;border-color:rgba(0,0,0,0.2)} .btn-instagram{color:#fff;background-color:#3f729b;border-color:rgba(0,0,0,0.2)}.btn-instagram:hover,.btn-instagram:focus,.btn-instagram:active,.btn-instagram.active,.open .dropdown-toggle.btn-instagram{color:#fff;background-color:#335d7e;border-color:rgba(0,0,0,0.2)} .btn-instagram:active,.btn-instagram.active,.open .dropdown-toggle.btn-instagram{background-image:none} .btn-instagram.disabled,.btn-instagram[disabled],fieldset[disabled] .btn-instagram,.btn-instagram.disabled:hover,.btn-instagram[disabled]:hover,fieldset[disabled] .btn-instagram:hover,.btn-instagram.disabled:focus,.btn-instagram[disabled]:focus,fieldset[disabled] .btn-instagram:focus,.btn-instagram.disabled:active,.btn-instagram[disabled]:active,fieldset[disabled] .btn-instagram:active,.btn-instagram.disabled.active,.btn-instagram[disabled].active,fieldset[disabled] .btn-instagram.active{background-color:#3f729b;border-color:rgba(0,0,0,0.2)} .btn-linkedin{color:#fff;background-color:#007bb6;border-color:rgba(0,0,0,0.2)}.btn-linkedin:hover,.btn-linkedin:focus,.btn-linkedin:active,.btn-linkedin.active,.open .dropdown-toggle.btn-linkedin{color:#fff;background-color:#005f8d;border-color:rgba(0,0,0,0.2)} .btn-linkedin:active,.btn-linkedin.active,.open .dropdown-toggle.btn-linkedin{background-image:none} .btn-linkedin.disabled,.btn-linkedin[disabled],fieldset[disabled] .btn-linkedin,.btn-linkedin.disabled:hover,.btn-linkedin[disabled]:hover,fieldset[disabled] .btn-linkedin:hover,.btn-linkedin.disabled:focus,.btn-linkedin[disabled]:focus,fieldset[disabled] .btn-linkedin:focus,.btn-linkedin.disabled:active,.btn-linkedin[disabled]:active,fieldset[disabled] .btn-linkedin:active,.btn-linkedin.disabled.active,.btn-linkedin[disabled].active,fieldset[disabled] .btn-linkedin.active{background-color:#007bb6;border-color:rgba(0,0,0,0.2)} .btn-twitter{color:#fff;background-color:#55acee;border-color:rgba(0,0,0,0.2)}.btn-twitter:hover,.btn-twitter:focus,.btn-twitter:active,.btn-twitter.active,.open .dropdown-toggle.btn-twitter{color:#fff;background-color:#309aea;border-color:rgba(0,0,0,0.2)} .btn-twitter:active,.btn-twitter.active,.open .dropdown-toggle.btn-twitter{background-image:none} .btn-twitter.disabled,.btn-twitter[disabled],fieldset[disabled] .btn-twitter,.btn-twitter.disabled:hover,.btn-twitter[disabled]:hover,fieldset[disabled] .btn-twitter:hover,.btn-twitter.disabled:focus,.btn-twitter[disabled]:focus,fieldset[disabled] .btn-twitter:focus,.btn-twitter.disabled:active,.btn-twitter[disabled]:active,fieldset[disabled] .btn-twitter:active,.btn-twitter.disabled.active,.btn-twitter[disabled].active,fieldset[disabled] .btn-twitter.active{background-color:#55acee;border-color:rgba(0,0,0,0.2)} a { text-decoration: none; } body { font-family: 'Raleway', sans-serif; } `}</style> </div> ); } } export default Profile;
node_modules/react-tools/src/utils/Transaction.js
rblin081/drafting-client
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ 'use strict'; var invariant = require('invariant'); /** * `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 = []; } else { this.wrapperInitData.length = 0; } 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. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} args... Arguments to pass to the method (optional). * Helps prevent need to bind in many cases. * @return Return value from `method`. */ perform: function(method, scope, a, b, c, d, e, f) { invariant( !this.isInTransaction(), 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.' ); 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) { invariant( this.isInTransaction(), 'Transaction.closeAll(): Cannot close transaction when none are open.' ); 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 occured. */ OBSERVED_ERROR: {} }; module.exports = Transaction;
src/components/common/BookDeleteModal.js
sergey-shulyak/simple-quote
import React from 'react'; const BookDeleteModal = ({ book, handleBookDelete }) => { return ( <div className="ui tiny modal book delete confirm"> <div className="header"> Delete {book.title} </div> <div className="content"> <div className="description"> Are you sure you want to delete this book? </div> </div> <div className="actions"> <button className="ui black basic deny button"> Cancel </button> <button className="ui negative button" onClick={handleBookDelete}> Delete </button> </div> </div> ); }; export default BookDeleteModal;
node_modules/react-icons/io/map.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const IoMap = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m34.5 10.7c0.3 0.2 0.5 0.6 0.5 1.1v22c0 0.4-0.2 0.8-0.5 1-0.2 0.1-0.4 0.2-0.6 0.2-0.2 0-0.5 0-0.6-0.2l-7.6-5.1-7.6 5.1c-0.4 0.3-0.8 0.3-1.1 0l-7.6-5.1-7.6 5.1c-0.4 0.3-0.8 0.3-1.2 0s-0.6-0.6-0.6-1v-22c0-0.5 0.2-0.9 0.5-1.1l8.3-5.5c0.3-0.3 0.7-0.3 1.1 0l7.6 5.1 7.7-5.1c0.3-0.3 0.7-0.3 1.1 0z m-26.5 16.9v-18.9l-5.5 3.9v18.9z m2.5 0l5.8 3.8v-10.1l-0.4 0.9c-0.5-0.2-1-0.5-1.5-0.8l0.6-1c0.4 0.2 0.9 0.5 1.3 0.6v-8.5l-5.8-3.8v7.9c0.4 0.1 0.7 0.3 1.1 0.5l-0.8 1c-0.1-0.1-0.2-0.1-0.3-0.1v9.6z m8.3 3.8l5.7-3.8v-8.5c0 0-0.1 0-0.1 0.1l-0.5 0.5-0.9-0.9 0.4-0.4c0.3-0.3 0.4-0.6 0.7-0.8l0.4 0.4v-9.3l-5.7 3.8v8.8h0.5l0.2 1.1c-0.2 0-0.4 0.1-0.7 0.1h0v8.9z m13.7 0v-18.9l-5.5-3.8v6.8c0.2 0 0.3 0 0.6-0.1l0.3 1.2c-0.3 0.1-0.6 0.1-0.9 0.3v10.7z m-24.9-14.1c-0.3 0-0.9 0.4-1.1 0.5l-0.9-0.9c0.3-0.3 0.7-0.5 1-0.6 0.2-0.2 0.4-0.3 0.7-0.4l0.4 1.2c-0.2 0.1 0 0.1-0.1 0.2z m13.1 3.5c0.4-0.3 0.8-0.4 1.2-0.8l0.8 0.9c-0.4 0.5-0.9 0.8-1.4 1.1z m-15.5-0.8v0.1l-1.1-0.4v-0.1c0.1-0.5 0.3-1 0.7-1.6l1 0.7c-0.3 0.4-0.4 0.8-0.6 1.3z m7.8-1.4c0.2 0.3 0.5 0.6 0.8 0.9l-0.8 0.9c-0.3-0.3-0.7-0.7-1-1l-0.2-0.3 0.9-0.8c0.1 0.1 0.2 0.2 0.3 0.3z m16.4-0.6l-0.9-1 0.8-0.8-0.8-0.7 0.9-1 0.8 0.9 0.8-0.9 0.9 1-0.8 0.7 0.8 0.8-0.9 1-0.8-0.9z"/></g> </Icon> ) export default IoMap
src/svg-icons/navigation/fullscreen-exit.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationFullscreenExit = (props) => ( <SvgIcon {...props}> <path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/> </SvgIcon> ); NavigationFullscreenExit = pure(NavigationFullscreenExit); NavigationFullscreenExit.displayName = 'NavigationFullscreenExit'; NavigationFullscreenExit.muiName = 'SvgIcon'; export default NavigationFullscreenExit;
app/extensions/More/index-nativegrid.js
typesettin/manuscript
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ //TO DO: https://github.com/clh161/react-native-easy-grid-view import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, Image, Platform } from 'react-native'; // import styles from '../../components/Styles/shared'; import { Button, // Card, SocialIcon, List, ListItem, ListView, PricingCard } from 'react-native-elements'; import GridView from 'react-native-grid-view' import in_theaters from './in_theaters.json' console.log('in_theaters',in_theaters) var PAGE_SIZE = 25; var MOVIES_PER_ROW = 3; class Movie extends Component { render() { return ( <View style={styles.movie} > <Image source={{uri: this.props.movie.posters.thumbnail}} style={styles.thumbnail} /> <View > <Text style={styles.title} numberOfLines={3}>{this.props.movie.title}</Text> <Text style={styles.year}>{this.props.movie.year}</Text> </View> </View> ); } } class More extends Component{ constructor(props) { super(props); this.state = { dataSource: null, loaded: false, } } componentDidMount() { this.fetchData(); } fetchData() { this.setState({ dataSource: in_theaters.movies, loaded: true, }); } render() { if (!this.state.loaded) { return this.renderLoadingView(); } return ( <GridView items={this.state.dataSource} itemsPerRow={MOVIES_PER_ROW} renderItem={this.renderItem} style={styles.listView} /> ); } renderLoadingView() { return ( <View> <Text> Loading movies... </Text> </View> ); } renderItem(item) { return <Movie movie={item} key={item.id} /> } }; var styles = StyleSheet.create({ movie: { height: 150, flex: 1, alignItems: 'center', flexDirection: 'column', }, title: { fontSize: 10, marginBottom: 8, width: 90, textAlign: 'center', }, year: { textAlign: 'center', }, thumbnail: { width: 53, height: 81, }, listView: { paddingTop: 20, backgroundColor: '#F5FCFF', position: 'relative', flex:1 }, }); // class More extends Component { // constructor(){ // super(...arguments); // this.state = { // ranattr:'ok', // }; // } // render() { // return ( // <View style={ styles.container }> // <Text style={ styles.heading }>In the apps app</Text> // <Button // small // iconRight // icon={{ name: 'code', }} // title="Code" /> // <Button // small // iconRight // icon={{ name: 'share-apple', type: 'evilicon', }} // title="Share Apple" /> // <Button // small // iconRight // icon={{ name: 'battery-full', type: 'foundation', }} // title="Battery Full" /> // </View> // ); // } // } export default More;
app/javascript/src/components/charts/heatMap.js
michelson/chaskiq
// make sure parent container have a defined height when using // responsive component, otherwise height will be 0 and // no chart will be rendered. // website examples showcase many properties, // you'll often use just a few of them. import React from 'react' // import { ResponsiveCalendar } from '@nivo/calendar' import { ResponsiveCalendarCanvas } from '@nivo/calendar' // import { useTheme } from '@material-ui/core/styles'; export default function MyResponsiveCalendar ({ data, from, to }) { // const theme = useTheme(); const theme = { palette: { primary: { light: '#112343', main: '#123443' } } } return ( <ResponsiveCalendarCanvas data={data} from={from._d.toISOString()} to={to._d.toISOString()} colors={{ scheme: 'nivo' }} emptyColor="#eeeeee" colors={['#61cdbb', '#97e3d5', '#e8c1a0', '#f47560']} margin={{ top: 10, right: 20, bottom: 10, left: 20 }} yearSpacing={40} monthBorderColor="#000000" dayBorderWidth={2} dayBorderColor="#ffffff" theme={{ labels: { text: { fill: theme.palette.primary.light, fontSize: 11, fontFamily: 'Roboto, sans-serif', color: theme.palette.primary.light } }, legends: { text: { fill: theme.palette.primary.main, fontSize: 11 } }, tooltip: { container: { background: 'white', color: 'black', fontSize: 'inherit', borderRadius: '2px', boxShadow: '0 1px 2px rgba(0, 0, 0, 0.25)', padding: '5px 9px' }, basic: { whiteSpace: 'pre', display: 'flex', alignItems: 'center' }, table: {}, tableCell: { padding: '3px 5px' } } }} legends={[ { color: '#ff000', anchor: 'bottom-right', direction: 'row', translateY: 36, itemCount: 4, itemWidth: 42, itemHeight: 36, itemsSpacing: 14, itemDirection: 'right-to-left' } ]} /> ) }
src/components/pages/Admin/Services/AdminServices.js
ESTEBANMURUZABAL/bananaStore
/** * Imports */ import React from 'react'; import connectToStores from 'fluxible-addons-react/connectToStores'; import {FormattedMessage} from 'react-intl'; import {Link} from 'react-router'; // Flux import ServicesAddStore from '../../../../stores/Services/ServicesAddStore'; import ServicesListStore from '../../../../stores/Services/ServicesListStore'; import ServicesStore from '../../../../stores/Services/ServicesStore'; import IntlStore from '../../../../stores/Application/IntlStore'; import addService from '../../../../actions/Admin/addService'; import fetchServices from '../../../../actions/Services/fetchServices'; // Required components import Button from '../../../common/buttons/Button'; import Heading from '../../../common/typography/Heading'; import Label from '../../../common/indicators/Label'; import Modal from '../../../common/modals/Modal'; import StatusIndicator from '../../../common/indicators/StatusIndicator'; import Table from '../../../common/tables/Table'; import Text from '../../../common/typography/Text'; import AdminServicesAddForm from './AdminServicesAddForm'; // Translation data for this component import intlData from './AdminServices.intl'; /** * Component */ class AdminServices extends React.Component { static contextTypes = { executeAction: React.PropTypes.func.isRequired, getStore: React.PropTypes.func.isRequired, router: React.PropTypes.func.isRequired }; //*** Required Data ***// static fetchData = function (context, params, query, done) { context.executeAction(fetchServices, {}, done); }; //*** Initial State ***// state = { addService: this.context.getStore(ServicesAddStore).getState(), services: this.context.getStore(ServicesListStore).getServices(), showNewServiceModal: false }; //*** Component Lifecycle ***// componentDidMount() { // Component styles require('./AdminServices.scss'); } componentWillReceiveProps(nextProps) { // If new Service was being added and was successful, redirect to // Service edit page if (this.state.addService.loading === true && nextProps._addService.loading === false && !nextProps._addService.error) { let params = { locale: this.context.getStore(IntlStore).getCurrentLocale(), serviceId: nextProps._addService.service.id }; this.context.router.transitionTo('adm-service-edit', params); } // Update state this.setState({ addService: nextProps._addService, services: nextProps._services }); } //*** View Controllers ***// handleNewServiceClick = () => { this.setState({showNewServiceModal: true}); }; handleNewServiceCloseClick = () => { this.setState({showNewServiceModal: false}); }; handleNewServiceSubmitClick = (data) => { this.context.executeAction(addService, data); }; //*** Template ***// render() { // // Helper methods & variables // let intlStore = this.context.getStore(IntlStore); let routeParams = {locale: this.context.getStore(IntlStore).getCurrentLocale()}; // Base route params let headings = [ <FormattedMessage message={intlStore.getMessage(intlData, 'nameHeading')} locales={intlStore.getCurrentLocale()} />, <FormattedMessage message={intlStore.getMessage(intlData, 'enabledHeading')} locales={intlStore.getCurrentLocale()} /> ]; let rows = this.state.services.map((service) => { return { data: [ <span className="admin-services__link"> <Link to="adm-service-edit" params={Object.assign({serviceId: service.id}, routeParams)}> <FormattedMessage message={intlStore.getMessage(service.name)} locales={intlStore.getCurrentLocale()} /> </Link> </span>, <StatusIndicator status={(service.enabled === true) ? 'success' : 'default'} /> ] }; }); let newServiceModal = () => { if (this.state.showNewServiceModal) { return ( <Modal title={intlStore.getMessage(intlData, 'newModalTitle')} onCloseClick={this.handleNewServiceCloseClick}> <AdminServicesAddForm loading={this.state.addService.loading} onCancelClick={this.handleNewServiceCloseClick} onSubmitClick={this.handleNewServiceSubmitClick} /> </Modal> ); } }; // // Return // return ( <div className="admin-services"> {newServiceModal()} <div className="admin-services__header"> <div className="admin-services__title"> <Heading size="medium"> <FormattedMessage message={intlStore.getMessage(intlData, 'title')} locales={intlStore.getCurrentLocale()} /> </Heading> </div> <div className="admin-services__toolbar"> <div className="admin-services__add-button"> <Button type="primary" onClick={this.handleNewServiceClick}> <FormattedMessage message={intlStore.getMessage(intlData, 'new')} locales={intlStore.getCurrentLocale()} /> </Button> </div> </div> </div> {!this.state.loading && this.state.services.length === 0 ? <div className="admin-services__no-results"> <Text size="small"> <FormattedMessage message={intlStore.getMessage(intlData, 'noResults')} locales={intlStore.getCurrentLocale()} /> </Text> </div> : <div className="admin-services__list"> <Table headings={headings} rows={rows} /> </div> } </div> ); } } /** * Flux */ AdminServices = connectToStores(AdminServices, [ServicesAddStore, ServicesListStore], (context) => { return { _addService: context.getStore(ServicesAddStore).getState(), _services: context.getStore(ServicesListStore).getServices() }; }); /** * Exports */ export default AdminServices;
ajax/libs/material-ui/4.10.1/Slider/Slider.min.js
cdnjs/cdnjs
"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard"),_interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=exports.styles=void 0;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")),_slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")),_objectWithoutProperties2=_interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")),_extends2=_interopRequireDefault(require("@babel/runtime/helpers/extends")),React=_interopRequireWildcard(require("react")),_propTypes=_interopRequireDefault(require("prop-types")),_clsx=_interopRequireDefault(require("clsx")),_utils=require("@material-ui/utils"),_withStyles=_interopRequireDefault(require("../styles/withStyles")),_useTheme=_interopRequireDefault(require("../styles/useTheme")),_colorManipulator=require("../styles/colorManipulator"),_useIsFocusVisible2=_interopRequireDefault(require("../utils/useIsFocusVisible")),_ownerDocument=_interopRequireDefault(require("../utils/ownerDocument")),_useEventCallback=_interopRequireDefault(require("../utils/useEventCallback")),_useForkRef=_interopRequireDefault(require("../utils/useForkRef")),_capitalize=_interopRequireDefault(require("../utils/capitalize")),_useControlled3=_interopRequireDefault(require("../utils/useControlled")),_ValueLabel=_interopRequireDefault(require("./ValueLabel"));function asc(e,t){return e-t}function clamp(e,t,a){return Math.min(Math.max(t,e),a)}function findClosest(e,n){return e.reduce(function(e,t,a){var r=Math.abs(n-t);return null===e||r<e.distance||r===e.distance?{distance:r,index:a}:e},null).index}function trackFinger(e,t){if(void 0!==t.current&&e.changedTouches){for(var a=0;a<e.changedTouches.length;a+=1){var r=e.changedTouches[a];if(r.identifier===t.current)return{x:r.clientX,y:r.clientY}}return!1}return{x:e.clientX,y:e.clientY}}function valueToPercent(e,t,a){return 100*(e-t)/(a-t)}function percentToValue(e,t,a){return(a-t)*e+t}function getDecimalPrecision(e){if(Math.abs(e)<1){var t=e.toExponential().split("e-"),a=t[0].split(".")[1];return(a?a.length:0)+parseInt(t[1],10)}var r=e.toString().split(".")[1];return r?r.length:0}function roundValueToStep(e,t,a){var r=Math.round((e-a)/t)*t+a;return Number(r.toFixed(getDecimalPrecision(t)))}function setValueIndex(e){var t=e.values,a=e.source,r=e.newValue,n=e.index;if(t[n]===r)return a;var o=t.slice();return o[n]=r,o}function focusThumb(e){var t=e.sliderRef,a=e.activeIndex,r=e.setActive;t.current.contains(document.activeElement)&&Number(document.activeElement.getAttribute("data-index"))===a||t.current.querySelector('[role="slider"][data-index="'.concat(a,'"]')).focus(),r&&r(a)}var axisProps={horizontal:{offset:function(e){return{left:"".concat(e,"%")}},leap:function(e){return{width:"".concat(e,"%")}}},"horizontal-reverse":{offset:function(e){return{right:"".concat(e,"%")}},leap:function(e){return{width:"".concat(e,"%")}}},vertical:{offset:function(e){return{bottom:"".concat(e,"%")}},leap:function(e){return{height:"".concat(e,"%")}}}},Identity=function(e){return e},styles=function(e){return{root:{height:2,width:"100%",boxSizing:"content-box",padding:"13px 0",display:"inline-block",position:"relative",cursor:"pointer",touchAction:"none",color:e.palette.primary.main,WebkitTapHighlightColor:"transparent","&$disabled":{pointerEvents:"none",cursor:"default",color:e.palette.grey[400]},"&$vertical":{width:2,height:"100%",padding:"0 13px"},"@media (pointer: coarse)":{padding:"20px 0","&$vertical":{padding:"0 20px"}},"@media print":{colorAdjust:"exact"}},colorPrimary:{},colorSecondary:{color:e.palette.secondary.main},marked:{marginBottom:20,"&$vertical":{marginBottom:"auto",marginRight:20}},vertical:{},disabled:{},rail:{display:"block",position:"absolute",width:"100%",height:2,borderRadius:1,backgroundColor:"currentColor",opacity:.38,"$vertical &":{height:"100%",width:2}},track:{display:"block",position:"absolute",height:2,borderRadius:1,backgroundColor:"currentColor","$vertical &":{width:2}},trackFalse:{"& $track":{display:"none"}},trackInverted:{"& $track":{backgroundColor:"light"===e.palette.type?(0,_colorManipulator.lighten)(e.palette.primary.main,.62):(0,_colorManipulator.darken)(e.palette.primary.main,.5)},"& $rail":{opacity:1}},thumb:{position:"absolute",width:12,height:12,marginLeft:-6,marginTop:-5,boxSizing:"border-box",borderRadius:"50%",outline:0,backgroundColor:"currentColor",display:"flex",alignItems:"center",justifyContent:"center",transition:e.transitions.create(["box-shadow"],{duration:e.transitions.duration.shortest}),"&::after":{position:"absolute",content:'""',borderRadius:"50%",left:-15,top:-15,right:-15,bottom:-15},"&$focusVisible,&:hover":{boxShadow:"0px 0px 0px 8px ".concat((0,_colorManipulator.fade)(e.palette.primary.main,.16)),"@media (hover: none)":{boxShadow:"none"}},"&$active":{boxShadow:"0px 0px 0px 14px ".concat((0,_colorManipulator.fade)(e.palette.primary.main,.16))},"&$disabled":{width:8,height:8,marginLeft:-4,marginTop:-3,"&:hover":{boxShadow:"none"}},"$vertical &":{marginLeft:-5,marginBottom:-6},"$vertical &$disabled":{marginLeft:-3,marginBottom:-4}},thumbColorPrimary:{},thumbColorSecondary:{"&$focusVisible,&:hover":{boxShadow:"0px 0px 0px 8px ".concat((0,_colorManipulator.fade)(e.palette.secondary.main,.16))},"&$active":{boxShadow:"0px 0px 0px 14px ".concat((0,_colorManipulator.fade)(e.palette.secondary.main,.16))}},active:{},focusVisible:{},valueLabel:{left:"calc(-50% - 4px)"},mark:{position:"absolute",width:2,height:2,borderRadius:1,backgroundColor:"currentColor"},markActive:{backgroundColor:e.palette.background.paper,opacity:.8},markLabel:(0,_extends2.default)((0,_extends2.default)({},e.typography.body2),{},{color:e.palette.text.secondary,position:"absolute",top:26,transform:"translateX(-50%)",whiteSpace:"nowrap","$vertical &":{top:"auto",left:26,transform:"translateY(50%)"},"@media (pointer: coarse)":{top:40,"$vertical &":{left:31}}}),markLabelActive:{color:e.palette.text.primary}}};exports.styles=styles;var Slider=React.forwardRef(function(e,t){var n=e["aria-label"],o=e["aria-labelledby"],l=e["aria-valuetext"],i=e.classes,a=e.className,r=e.color,u=void 0===r?"primary":r,s=e.component,c=void 0===s?"span":s,d=e.defaultValue,p=e.disabled,f=void 0!==p&&p,v=e.getAriaLabel,m=e.getAriaValueText,b=e.marks,y=void 0!==b&&b,h=e.max,_=void 0===h?100:h,x=e.min,g=void 0===x?0:x,T=e.name,k=e.onChange,R=e.onChangeCommitted,w=e.onMouseDown,C=e.orientation,L=void 0===C?"horizontal":C,E=e.scale,q=void 0===E?Identity:E,A=e.step,V=void 0===A?1:A,D=e.ThumbComponent,S=void 0===D?"span":D,I=e.track,M=void 0===I?"normal":I,F=e.value,P=e.ValueLabelComponent,O=void 0===P?_ValueLabel.default:P,$=e.valueLabelDisplay,N=void 0===$?"off":$,z=e.valueLabelFormat,j=void 0===z?Identity:z,B=(0,_objectWithoutProperties2.default)(e,["aria-label","aria-labelledby","aria-valuetext","classes","className","color","component","defaultValue","disabled","getAriaLabel","getAriaValueText","marks","max","min","name","onChange","onChangeCommitted","onMouseDown","orientation","scale","step","ThumbComponent","track","value","ValueLabelComponent","valueLabelDisplay","valueLabelFormat"]),W=(0,_useTheme.default)(),Y=React.useRef(),U=React.useState(-1),X=U[0],H=U[1],K=React.useState(-1),G=K[0],J=K[1],Q=(0,_useControlled3.default)({controlled:F,default:d,name:"Slider"}),Z=(0,_slicedToArray2.default)(Q,2),ee=Z[0],te=Z[1],ae=Array.isArray(ee),re=(re=ae?ee.slice().sort(asc):[ee]).map(function(e){return clamp(e,g,_)}),ne=!0===y&&null!==V?(0,_toConsumableArray2.default)(Array(Math.floor((_-g)/V)+1)).map(function(e,t){return{value:g+V*t}}):y||[],oe=(0,_useIsFocusVisible2.default)(),le=oe.isFocusVisible,ie=oe.onBlurVisible,ue=oe.ref,se=React.useState(-1),ce=se[0],de=se[1],pe=React.useRef(),fe=(0,_useForkRef.default)(ue,pe),ve=(0,_useForkRef.default)(t,fe),me=(0,_useEventCallback.default)(function(e){var t=Number(e.currentTarget.getAttribute("data-index"));le(e)&&de(t),J(t)}),be=(0,_useEventCallback.default)(function(){-1!==ce&&(de(-1),ie()),J(-1)}),ye=(0,_useEventCallback.default)(function(e){var t=Number(e.currentTarget.getAttribute("data-index"));J(t)}),he=(0,_useEventCallback.default)(function(){J(-1)}),_e="rtl"===W.direction,xe=(0,_useEventCallback.default)(function(e){var t,a,r=Number(e.currentTarget.getAttribute("data-index")),n=re[r],o=(_-g)/10,l=ne.map(function(e){return e.value}),i=l.indexOf(n),u=_e?"ArrowLeft":"ArrowRight",s=_e?"ArrowRight":"ArrowLeft";switch(e.key){case"Home":a=g;break;case"End":a=_;break;case"PageUp":V&&(a=n+o);break;case"PageDown":V&&(a=n-o);break;case u:case"ArrowUp":a=V?n+V:l[i+1]||l[l.length-1];break;case s:case"ArrowDown":a=V?n-V:l[i-1]||l[0];break;default:return}e.preventDefault(),V&&(a=roundValueToStep(a,V,g)),a=clamp(a,g,_),ae&&(a=setValueIndex({values:re,source:ee,newValue:t=a,index:r}).sort(asc),focusThumb({sliderRef:pe,activeIndex:a.indexOf(t)})),te(a),de(r),k&&k(e,a),R&&R(e,a)}),ge=React.useRef(),Te=L;_e&&"vertical"!==L&&(Te+="-reverse");function ke(e){var t,a,r=e.finger,n=e.move,o=void 0!==n&&n,l=e.values,i=e.source,u=pe.current.getBoundingClientRect(),s=u.width,c=u.height,d=u.bottom,p=u.left,f=0===Te.indexOf("vertical")?(d-r.y)/c:(r.x-p)/s;-1!==Te.indexOf("-reverse")&&(f=1-f),a=percentToValue(f,g,_),a=clamp(a=V?roundValueToStep(a,V,g):(t=ne.map(function(e){return e.value}))[findClosest(t,a)],g,_);var v,m=0;return ae&&(m=(a=setValueIndex({values:l,source:i,newValue:v=a,index:m=o?ge.current:findClosest(l,a)}).sort(asc)).indexOf(v),ge.current=m),{newValue:a,activeIndex:m}}var Re=(0,_useEventCallback.default)(function(e){var t,a,r,n=trackFinger(e,Y);n&&(a=(t=ke({finger:n,move:!0,values:re,source:ee})).newValue,r=t.activeIndex,focusThumb({sliderRef:pe,activeIndex:r,setActive:H}),te(a),k&&k(e,a))}),we=(0,_useEventCallback.default)(function(e){var t,a,r=trackFinger(e,Y);r&&(t=ke({finger:r,values:re,source:ee}).newValue,H(-1),"touchend"===e.type&&J(-1),R&&R(e,t),(a=(Y.current=void 0,_ownerDocument.default)(pe.current)).removeEventListener("mousemove",Re),a.removeEventListener("mouseup",we),a.removeEventListener("touchmove",Re),a.removeEventListener("touchend",we))}),Ce=(0,_useEventCallback.default)(function(e){e.preventDefault();var t=e.changedTouches[0];null!=t&&(Y.current=t.identifier);var a=trackFinger(e,Y),r=ke({finger:a,values:re,source:ee}),n=r.newValue,o=r.activeIndex;focusThumb({sliderRef:pe,activeIndex:o,setActive:H}),te(n),k&&k(e,n);var l=(0,_ownerDocument.default)(pe.current);l.addEventListener("touchmove",Re),l.addEventListener("touchend",we)});React.useEffect(function(){var e=pe.current;e.addEventListener("touchstart",Ce);var t=(0,_ownerDocument.default)(e);return function(){e.removeEventListener("touchstart",Ce),t.removeEventListener("mousemove",Re),t.removeEventListener("mouseup",we),t.removeEventListener("touchmove",Re),t.removeEventListener("touchend",we)}},[we,Re,Ce]);var Le=(0,_useEventCallback.default)(function(e){w&&w(e),e.preventDefault();var t=trackFinger(e,Y),a=ke({finger:t,values:re,source:ee}),r=a.newValue,n=a.activeIndex;focusThumb({sliderRef:pe,activeIndex:n,setActive:H}),te(r),k&&k(e,r);var o=(0,_ownerDocument.default)(pe.current);o.addEventListener("mousemove",Re),o.addEventListener("mouseup",we)}),Ee=valueToPercent(ae?re[0]:g,g,_),qe=valueToPercent(re[re.length-1],g,_)-Ee,Ae=(0,_extends2.default)((0,_extends2.default)({},axisProps[Te].offset(Ee)),axisProps[Te].leap(qe));return React.createElement(c,(0,_extends2.default)({ref:ve,className:(0,_clsx.default)(i.root,i["color".concat((0,_capitalize.default)(u))],a,f&&i.disabled,0<ne.length&&ne.some(function(e){return e.label})&&i.marked,!1===M&&i.trackFalse,"vertical"===L&&i.vertical,"inverted"===M&&i.trackInverted),onMouseDown:Le},B),React.createElement("span",{className:i.rail}),React.createElement("span",{className:i.track,style:Ae}),React.createElement("input",{value:re.join(","),name:T,type:"hidden"}),ne.map(function(e,t){var a=valueToPercent(e.value,g,_),r=axisProps[Te].offset(a),n=!1===M?-1!==re.indexOf(e.value):"normal"===M&&(ae?e.value>=re[0]&&e.value<=re[re.length-1]:e.value<=re[0])||"inverted"===M&&(ae?e.value<=re[0]||e.value>=re[re.length-1]:e.value>=re[0]);return React.createElement(React.Fragment,{key:e.value},React.createElement("span",{style:r,"data-index":t,className:(0,_clsx.default)(i.mark,n&&i.markActive)}),null!=e.label?React.createElement("span",{"aria-hidden":!0,"data-index":t,style:r,className:(0,_clsx.default)(i.markLabel,n&&i.markLabelActive)},e.label):null)}),re.map(function(e,t){var a=valueToPercent(e,g,_),r=axisProps[Te].offset(a);return React.createElement(O,{key:t,valueLabelFormat:j,valueLabelDisplay:N,className:i.valueLabel,value:"function"==typeof j?j(q(e),t):j,index:t,open:G===t||X===t||"on"===N,disabled:f},React.createElement(S,{className:(0,_clsx.default)(i.thumb,i["thumbColor".concat((0,_capitalize.default)(u))],X===t&&i.active,f&&i.disabled,ce===t&&i.focusVisible),tabIndex:f?null:0,role:"slider",style:r,"data-index":t,"aria-label":v?v(t):n,"aria-labelledby":o,"aria-orientation":L,"aria-valuemax":q(_),"aria-valuemin":q(g),"aria-valuenow":q(e),"aria-valuetext":m?m(q(e),t):l,onKeyDown:xe,onFocus:me,onBlur:be,onMouseOver:ye,onMouseLeave:he}))}))});"production"!==process.env.NODE_ENV&&(Slider.propTypes={"aria-label":(0,_utils.chainPropTypes)(_propTypes.default.string,function(e){return Array.isArray(e.value||e.defaultValue)&&null!=e["aria-label"]?new Error("Material-UI: You need to use the `getAriaLabel` prop instead of `aria-label` when using a range slider."):null}),"aria-labelledby":_propTypes.default.string,"aria-valuetext":(0,_utils.chainPropTypes)(_propTypes.default.string,function(e){return Array.isArray(e.value||e.defaultValue)&&null!=e["aria-valuetext"]?new Error("Material-UI: You need to use the `getAriaValueText` prop instead of `aria-valuetext` when using a range slider."):null}),classes:_propTypes.default.object.isRequired,className:_propTypes.default.string,color:_propTypes.default.oneOf(["primary","secondary"]),component:_propTypes.default.elementType,defaultValue:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.arrayOf(_propTypes.default.number)]),disabled:_propTypes.default.bool,getAriaLabel:_propTypes.default.func,getAriaValueText:_propTypes.default.func,marks:_propTypes.default.oneOfType([_propTypes.default.bool,_propTypes.default.array]),max:_propTypes.default.number,min:_propTypes.default.number,name:_propTypes.default.string,onChange:_propTypes.default.func,onChangeCommitted:_propTypes.default.func,onMouseDown:_propTypes.default.func,orientation:_propTypes.default.oneOf(["horizontal","vertical"]),scale:_propTypes.default.func,step:_propTypes.default.number,ThumbComponent:_propTypes.default.elementType,track:_propTypes.default.oneOf(["normal",!1,"inverted"]),value:_propTypes.default.oneOfType([_propTypes.default.number,_propTypes.default.arrayOf(_propTypes.default.number)]),ValueLabelComponent:_propTypes.default.elementType,valueLabelDisplay:_propTypes.default.oneOf(["on","auto","off"]),valueLabelFormat:_propTypes.default.oneOfType([_propTypes.default.string,_propTypes.default.func])});var _default=(0,_withStyles.default)(styles,{name:"MuiSlider"})(Slider);exports.default=_default;
packages/material-ui-icons/src/ToggleOnRounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17 7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h10c2.76 0 5-2.24 5-5s-2.24-5-5-5zm0 8c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z" /> , 'ToggleOnRounded');
src/app/index.js
isaacjoh/foreseehome-test
import React from 'react'; import {render} from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import Main from './Main'; // Our custom react component // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); // Render the main app react component into the app div. // For more details see: https://facebook.github.io/react/docs/top-level-api.html#react.render render(<Main />, document.getElementById('app'));
core/static/admin/src/redux/utils/createDevToolsWindow.js
tjcunliffe/hoverfly
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import DevTools from '../../containers/DevToolsWindow' export default function createDevToolsWindow (store) { const win = window.open( null, 'redux-devtools', // give it a name so it reuses the same window `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no` ) // reload in case it's reusing the same window with the old content win.location.reload() // wait a little bit for it to reload, then render setTimeout(() => { // Wait for the reload to prevent: // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element." win.document.write('<div id="react-devtools-root"></div>') win.document.body.style.margin = '0' ReactDOM.render( <Provider store={store}> <DevTools /> </Provider> , win.document.getElementById('react-devtools-root') ) }, 10) }
effcalculator/frontend/assets/js/routes/detectors/components/DetectorAnimatedList.js
alvcarmona/efficiencycalculatorweb
import React, {Component} from 'react' import {ListGroup, ListGroupItem, Glyphicon} from 'react-bootstrap' export default class DetectorAnimatedlistComponent extends Component { // Stiles in **** Detector list **** section App.css constructor(props) { super(props) this.state = {multipleSelectMode: false, selected: {}} ///adesfasdf } componentDidUpdate() { // adds show class to trigger animation let element = document.getElementById('detectorList').lastChild setTimeout(function () { element.className = element.className + " show"; }, 10); } componentDidMount() { // adds show class in first renderization let elements = document.getElementById('detectorList').childNodes for (let i = 0; i < elements.length; i++) { elements[i].className = elements[i].className + " show" } } onItemClick(d) { console.log("selected " + d) let selected = {} if (this.state.selected[d.id]) { document.getElementById('list' + d.id).style.backgroundColor = 'white'; document.getElementById('list' + d.id).style.width = "100%" this.props.selectDetectors({}) } else { let c = document.getElementById('detectorList').children for (let it of c){ it.style.backgroundColor = 'white'; it.style.width = "100%" } selected[d.id] = d document.getElementById('list' + d.id).style.backgroundColor = '#ceeff5'; document.getElementById('list' + d.id).style.width = "110%" this.props.selectDetectors(selected) } } render() { const elementStyle = { fontSize: '15px', textAlign: 'left', }; const childElements = this.props.detectors.map(u => { return ( <ListGroupItem id={'list' + u.id} className='detectorlistElement' key={u.id} style={elementStyle} onClick={() => this.onItemClick(u)}> <Glyphicon glyph="tag"/> {u.name} {/* <Link to={`/detectors/${u.id}`}> <Glyphicon glyph="list-alt"/></Link>*/} </ListGroupItem> ); }); return ( <ListGroup id={"detectorList"}> {childElements} </ListGroup> ); } }
examples/websdk-samples/LayerReactNativeSample/index.ios.js
layerhq/layer-js-sampleapps
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Modal, StatusBar } from 'react-native'; import { Client, Query } from 'layer-websdk/index-react-native.js'; import LayerHelper from './src/layer_helper.js' import configureStore from './src/store/configureStore'; import { ownerSet } from './src/actions/messenger'; import ChatView from './src/ChatView' import LoginDialog from './src/LoginDialog' const appId = LayerHelper.appId; export default class LayerReactNativeSample extends Component { constructor(props) { super(props); this.state = { loggedIn: false, } /** * Initialize Layer Client with `appId` */ this.client = new Client({ appId: appId }); /** * Client authentication challenge. * Sign in to Layer sample identity provider service. * * See http://static.layer.com/sdk/docs/#!/api/layer.Client-event-challenge */ this.client.on('challenge', e => { LayerHelper.getIdentityToken(e.nonce, e.callback); }); this.client.on('ready', () => { this.setState({loggedIn: true}); this.store.dispatch(ownerSet(this.client.user.toObject())); StatusBar.setNetworkActivityIndicatorVisible(false); }); /** * Share the client with the middleware layer */ this.store = configureStore(this.client); /** * validate that the sample data has been properly set up */ LayerHelper.validateSetup(this.client); } login() { /** * Start authentication */ StatusBar.setNetworkActivityIndicatorVisible(true); this.client.connect(); } render() { return ( <View style={styles.container}> <ChatView client={this.client} store={this.store} /> <Modal animationType={"slide"} transparent={true} visible={!this.state.loggedIn} > <View style={styles.modalBackground}> <LoginDialog onLogin={this.login.bind(this)} /> </View> </Modal> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1 }, modalBackground: { flex: 1, backgroundColor: 'rgba(0,0,0,0.5)', justifyContent: 'center' }, }); AppRegistry.registerComponent('LayerReactNativeSample', () => LayerReactNativeSample);
src/components/Messages/Success/index.js
auth0-extensions/auth0-extension-ui
import React, { Component } from 'react'; import Alert from '../Alert'; class Success extends Component { static defaultProps = { show: true } render() { return ( <Alert show={this.props.show} type="success" title="Well done!" message={this.props.message} onDismiss={this.props.onDismiss} > {this.props.children} </Alert> ); } } Success.propTypes = { show: React.PropTypes.bool, message: React.PropTypes.string, onDismiss: React.PropTypes.func, children: React.PropTypes.node }; export default Success;
src/components/Header/Header.js
quasicrial/quasicrial
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import { defineMessages, FormattedMessage } from 'react-intl'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Header.css'; import Link from '../Link'; import Navigation from '../Navigation'; import LanguageSwitcher from '../LanguageSwitcher'; import logoUrl from './logo-small.png'; import logoUrl2x from './logo-small@2x.png'; const messages = defineMessages({ brand: { id: 'header.brand', defaultMessage: 'Your Company Brand', description: 'Brand name displayed in header', }, bannerTitle: { id: 'header.banner.title', defaultMessage: 'React', description: 'Title in page header', }, bannerDesc: { id: 'header.banner.desc', defaultMessage: 'Complex web apps made easy', description: 'Description in header', }, }); class Header extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <Navigation className={s.nav} /> <Link className={s.brand} to="/"> <img src={logoUrl} srcSet={`${logoUrl2x} 2x`} width="38" height="38" alt="React" /> <span className={s.brandTxt}> <FormattedMessage {...messages.brand} /> </span> </Link> <LanguageSwitcher /> <div className={s.banner}> <h1 className={s.bannerTitle}> <FormattedMessage {...messages.bannerTitle} /> </h1> <FormattedMessage tagName="p" {...messages.bannerDesc} /> </div> </div> </div> ); } } export default withStyles(s)(Header);
flow-typed/npm/react-dnd_vx.x.x.js
captainsafia/nteract
// flow-typed signature: 69a85c64ae3cdb527094585e3a41c762 // flow-typed version: <<STUB>>/react-dnd_v^2.4.0/flow_v0.54.0 /** * This is an autogenerated libdef stub for: * * 'react-dnd' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'react-dnd' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'react-dnd/dist/ReactDnD' { declare module.exports: any; } declare module 'react-dnd/dist/ReactDnD.min' { declare module.exports: any; } declare module 'react-dnd/lib/areOptionsEqual' { declare module.exports: any; } declare module 'react-dnd/lib/createSourceConnector' { declare module.exports: any; } declare module 'react-dnd/lib/createSourceFactory' { declare module.exports: any; } declare module 'react-dnd/lib/createSourceMonitor' { declare module.exports: any; } declare module 'react-dnd/lib/createTargetConnector' { declare module.exports: any; } declare module 'react-dnd/lib/createTargetFactory' { declare module.exports: any; } declare module 'react-dnd/lib/createTargetMonitor' { declare module.exports: any; } declare module 'react-dnd/lib/decorateHandler' { declare module.exports: any; } declare module 'react-dnd/lib/DragDropContext' { declare module.exports: any; } declare module 'react-dnd/lib/DragDropContextProvider' { declare module.exports: any; } declare module 'react-dnd/lib/DragLayer' { declare module.exports: any; } declare module 'react-dnd/lib/DragSource' { declare module.exports: any; } declare module 'react-dnd/lib/DropTarget' { declare module.exports: any; } declare module 'react-dnd/lib/index' { declare module.exports: any; } declare module 'react-dnd/lib/registerSource' { declare module.exports: any; } declare module 'react-dnd/lib/registerTarget' { declare module.exports: any; } declare module 'react-dnd/lib/utils/checkDecoratorArguments' { declare module.exports: any; } declare module 'react-dnd/lib/utils/cloneWithRef' { declare module.exports: any; } declare module 'react-dnd/lib/utils/isValidType' { declare module.exports: any; } declare module 'react-dnd/lib/utils/shallowEqual' { declare module.exports: any; } declare module 'react-dnd/lib/utils/shallowEqualScalar' { declare module.exports: any; } declare module 'react-dnd/lib/wrapConnectorHooks' { declare module.exports: any; } // Filename aliases declare module 'react-dnd/dist/ReactDnD.js' { declare module.exports: $Exports<'react-dnd/dist/ReactDnD'>; } declare module 'react-dnd/dist/ReactDnD.min.js' { declare module.exports: $Exports<'react-dnd/dist/ReactDnD.min'>; } declare module 'react-dnd/lib/areOptionsEqual.js' { declare module.exports: $Exports<'react-dnd/lib/areOptionsEqual'>; } declare module 'react-dnd/lib/createSourceConnector.js' { declare module.exports: $Exports<'react-dnd/lib/createSourceConnector'>; } declare module 'react-dnd/lib/createSourceFactory.js' { declare module.exports: $Exports<'react-dnd/lib/createSourceFactory'>; } declare module 'react-dnd/lib/createSourceMonitor.js' { declare module.exports: $Exports<'react-dnd/lib/createSourceMonitor'>; } declare module 'react-dnd/lib/createTargetConnector.js' { declare module.exports: $Exports<'react-dnd/lib/createTargetConnector'>; } declare module 'react-dnd/lib/createTargetFactory.js' { declare module.exports: $Exports<'react-dnd/lib/createTargetFactory'>; } declare module 'react-dnd/lib/createTargetMonitor.js' { declare module.exports: $Exports<'react-dnd/lib/createTargetMonitor'>; } declare module 'react-dnd/lib/decorateHandler.js' { declare module.exports: $Exports<'react-dnd/lib/decorateHandler'>; } declare module 'react-dnd/lib/DragDropContext.js' { declare module.exports: $Exports<'react-dnd/lib/DragDropContext'>; } declare module 'react-dnd/lib/DragDropContextProvider.js' { declare module.exports: $Exports<'react-dnd/lib/DragDropContextProvider'>; } declare module 'react-dnd/lib/DragLayer.js' { declare module.exports: $Exports<'react-dnd/lib/DragLayer'>; } declare module 'react-dnd/lib/DragSource.js' { declare module.exports: $Exports<'react-dnd/lib/DragSource'>; } declare module 'react-dnd/lib/DropTarget.js' { declare module.exports: $Exports<'react-dnd/lib/DropTarget'>; } declare module 'react-dnd/lib/index.js' { declare module.exports: $Exports<'react-dnd/lib/index'>; } declare module 'react-dnd/lib/registerSource.js' { declare module.exports: $Exports<'react-dnd/lib/registerSource'>; } declare module 'react-dnd/lib/registerTarget.js' { declare module.exports: $Exports<'react-dnd/lib/registerTarget'>; } declare module 'react-dnd/lib/utils/checkDecoratorArguments.js' { declare module.exports: $Exports<'react-dnd/lib/utils/checkDecoratorArguments'>; } declare module 'react-dnd/lib/utils/cloneWithRef.js' { declare module.exports: $Exports<'react-dnd/lib/utils/cloneWithRef'>; } declare module 'react-dnd/lib/utils/isValidType.js' { declare module.exports: $Exports<'react-dnd/lib/utils/isValidType'>; } declare module 'react-dnd/lib/utils/shallowEqual.js' { declare module.exports: $Exports<'react-dnd/lib/utils/shallowEqual'>; } declare module 'react-dnd/lib/utils/shallowEqualScalar.js' { declare module.exports: $Exports<'react-dnd/lib/utils/shallowEqualScalar'>; } declare module 'react-dnd/lib/wrapConnectorHooks.js' { declare module.exports: $Exports<'react-dnd/lib/wrapConnectorHooks'>; }
test/browser/helpers.js
jeffvan576/react-data-grid
var mergeInto = require("../../src/mergeInto"); var Grid = require('../../src/Grid'); var React = require('react'); var data = []; for (var i = 0; i < 2000; i++) { data.push({ 'key': i, 'supplier':{'value':'Supplier ' + i, 'editing':true}, 'format': 'fmt ' + i, 'start':'start', 'end':'end', 'price':i }); }; function rows(start, end) { return data.slice(start, end); } var columns = [ { idx: 0, name: 'Supplier', key: 'supplier', width: 300, locked: true, }, { idx: 1, name: 'Format', key: 'format', width: 350, }, { idx: 2, name: 'Start', key: 'start', width: 250, }, { idx: 3, name: 'End', key: 'end', width: 250, }, { idx: 4, name: 'Cost', key: 'cost', width: 200, } ]; var getGrid = function(args) { args = args || {}; mergeInto(args, { columns: columns, rows: rows, removeFreezeCols: false, dataLength: data.length, rowHeight:40 }); return Grid({columns:args.columns, rows: args.rows, length: args.dataLength, height: args.height}); }; var renderGrid = function(args) { return React.render(getGrid(args), document.getElementById(args.containerId)); }; module.exports = { getGrid: getGrid, renderGrid: renderGrid };
react-progressive-hydration/babel.config.js
GoogleChromeLabs/progressive-rendering-frameworks-samples
module.exports = { presets: [ ['@babel/preset-env', { useBuiltIns: 'usage', corejs: 3, modules: false, loose: true }], '@babel/preset-react' ], plugins: [ '@babel/syntax-dynamic-import' ] };
ajax/libs/yui/3.10.2/datatable-body/datatable-body-debug.js
NMastracchio/cdnjs
YUI.add('datatable-body', function (Y, NAME) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object, valueRegExp = /\{value\}/g; /** 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. A column `formatter` can be: * a function, as described below. * a string which can be: * the name of a pre-defined formatter function which can be located in the `Y.DataTable.BodyView.Formatters` hash using the value of the `formatter` property as the index. * A template that can use the `{value}` placeholder to include the value for the current cell or the name of any field in the underlaying model also enclosed in curly braces. Any number and type of these placeholders can be used. 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._afterRenderCleanup(); 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 () { 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 () { //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 () { 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._formatterFn) { formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; // Formatters can either return a value value = col._formatterFn.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, F = Y.DataTable.BodyView.Formatters, i, len, col, key, token, headers, tokenValues, formatter; for (i = 0, len = columns.length; i < len; ++i) { col = columns[i]; key = col.key; token = col._id || key; formatter = col.formatter; // 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 (formatter) { if (Lang.isFunction(formatter)) { col._formatterFn = formatter; } else if (formatter in F) { col._formatterFn = F[formatter].call(this.host || this, col); } else { tokenValues.content = formatter.replace(valueRegExp, tokenValues.content); } } 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 }); }, /** Cleans up temporary values created during rendering. @method _afterRenderCleanup @private */ _afterRenderCleanup: function () { var columns = this.get('columns'), i, len = columns.length; for (i = 0;i < len; i+=1) { delete columns[i]._formatterFn; } }, /** 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 },{ /** Hash of formatting functions for cell contents. This property can be populated with a hash of formatting functions by the developer or a set of pre-defined functions can be loaded via the `datatable-formatters` module. See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html) @property Formatters @type Object @since 3.8.0 @static **/ Formatters: {} }); }, '@VERSION@', {"requires": ["datatable-core", "view", "classnamemanager"]});
node_modules/react-icons/io/social-usd.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const IoSocialUsd = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m32.1 23.7c0.2 0.8 0.4 1.5 0.4 2.2 0 1.7-0.4 3-1.1 4.2s-1.6 2-2.7 2.7-2.5 1.3-3.9 1.7c-0.8 0.1-1.5 0.2-2.3 0.3v2.7h-5v-2.7c-0.7-0.1-1.5-0.3-2.2-0.5-1.6-0.4-2.8-0.9-4-1.8s-2-1.9-2.7-3.2c-0.6-1.3-1-2.7-1.1-4.3h5.4c0 0.9 0.1 1.9 0.5 2.6 0.4 0.8 1 1.3 1.7 1.8s1.5 0.8 2.4 1.1v-9.4c-0.6-0.2-1.4-0.3-2.1-0.5-1.3-0.3-2.4-0.7-3.2-1.2s-1.6-1.2-2.1-1.8-0.9-1.4-1.1-2.1-0.3-1.4-0.3-2.1c0-1.4 0.3-2.7 0.9-3.8s1.5-1.9 2.6-2.6 2.3-1.3 3.6-1.6c0.5-0.2 1.2-0.2 1.7-0.3v-2.6h5v2.6c0.7 0.1 1.3 0.3 1.9 0.4 1.4 0.4 2.6 1 3.7 1.8s2 1.7 2.6 2.9c0.6 1 0.9 2.1 0.9 3.6h-5.3c-0.3-1.7-1-2.9-2.1-3.6-0.5-0.4-1-0.7-1.7-0.8v8.3c0.7 0.1 1.3 0.3 2 0.4 0.9 0.3 1.7 0.5 2.1 0.6 1 0.3 1.8 0.7 2.5 1.1 0.8 0.6 1.4 1.1 1.9 1.8s0.9 1.3 1.1 2.1z m-14.6-7.3v-7.2c-0.5 0.2-1.2 0.3-1.6 0.6-0.6 0.3-1 0.7-1.4 1.1s-0.5 1.1-0.5 1.8c0 1.1 0.3 1.9 1 2.5 0.6 0.5 1.6 0.9 2.5 1.2z m9.3 11.6c0.2-0.5 0.3-1 0.3-1.5 0-1.1-0.2-1.9-0.8-2.4s-1.1-0.9-1.8-1.1-1.2-0.4-2-0.7v8.4c0.5-0.1 0.8-0.2 1.1-0.2 0.9-0.3 1.6-0.7 2.1-1s0.9-0.9 1.1-1.5z"/></g> </Icon> ) export default IoSocialUsd
src/svg-icons/device/signal-wifi-4-bar.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi4Bar = (props) => ( <SvgIcon {...props}> <path d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/> </SvgIcon> ); DeviceSignalWifi4Bar = pure(DeviceSignalWifi4Bar); DeviceSignalWifi4Bar.displayName = 'DeviceSignalWifi4Bar'; DeviceSignalWifi4Bar.muiName = 'SvgIcon'; export default DeviceSignalWifi4Bar;
src/client/menu.js
uptownhr/hacker-menu
import React from 'react' export default class Menu extends React.Component { handleOnClick (e) { e.preventDefault() this.props.onQuitClick() } render () { var statusText = 'v' + this.props.version var buttonText = 'Quit' if (this.props.status === 'update-available') { statusText += ' (v' + this.props.upgradeVersion + ' available, restart to upgrade)' buttonText = 'Restart' } return ( <div className='bar bar-standard bar-footer'> <em className='status pull-left'>{statusText}</em> <button className='btn pull-right' onClick={this.handleOnClick.bind(this)}> {buttonText} </button> </div> ) } } Menu.propTypes = { status: React.PropTypes.string.isRequired, version: React.PropTypes.string.isRequired, upgradeVersion: React.PropTypes.string.isRequired, onQuitClick: React.PropTypes.func.isRequired }
src/svg-icons/action/lock-open.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLockOpen = (props) => ( <SvgIcon {...props}> <path d="M12 17c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm6-9h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h1.9c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm0 12H6V10h12v10z"/> </SvgIcon> ); ActionLockOpen = pure(ActionLockOpen); ActionLockOpen.displayName = 'ActionLockOpen'; ActionLockOpen.muiName = 'SvgIcon'; export default ActionLockOpen;
src/TimePicker/TimePickerDialog.js
pradel/material-ui
import React from 'react'; import EventListener from 'react-event-listener'; import keycode from 'keycode'; import Clock from './Clock'; import Dialog from '../Dialog'; import FlatButton from '../FlatButton'; class TimePickerDialog extends React.Component { static propTypes = { autoOk: React.PropTypes.bool, cancelLabel: React.PropTypes.node, format: React.PropTypes.oneOf(['ampm', '24hr']), initialTime: React.PropTypes.object, okLabel: React.PropTypes.node, onAccept: React.PropTypes.func, onDismiss: React.PropTypes.func, onShow: React.PropTypes.func, }; static defaultProps = { okLabel: 'OK', cancelLabel: 'Cancel', }; static contextTypes = { muiTheme: React.PropTypes.object.isRequired, }; state = { open: false, }; getTheme() { return this.context.muiTheme.timePicker; } show() { if (this.props.onShow && !this.state.open) this.props.onShow(); this.setState({ open: true, }); } dismiss() { if (this.props.onDismiss && this.state.open) this.props.onDismiss(); this.setState({ open: false, }); } handleRequestClose = () => { this.dismiss(); }; handleTouchTapCancel = () => { this.dismiss(); }; handleTouchTapOK = () => { this.dismiss(); if (this.props.onAccept) { this.props.onAccept(this.refs.clock.getSelectedTime()); } }; handleKeyUp = (event) => { switch (keycode(event)) { case 'enter': this.handleTouchTapOK(); break; } }; render() { const { initialTime, onAccept, // eslint-disable-line no-unused-vars format, autoOk, okLabel, cancelLabel, ...other, } = this.props; const styles = { root: { fontSize: 14, color: this.getTheme().clockColor, }, dialogContent: { width: 280, }, body: { padding: 0, }, }; const actions = [ <FlatButton key={0} label={cancelLabel} primary={true} onTouchTap={this.handleTouchTapCancel} />, <FlatButton key={1} label={okLabel} primary={true} onTouchTap={this.handleTouchTapOK} />, ]; const onClockChangeMinutes = autoOk === true ? this.handleTouchTapOK : undefined; const open = this.state.open; return ( <Dialog {...other} ref="dialogWindow" style={styles.root} bodyStyle={styles.body} actions={actions} contentStyle={styles.dialogContent} repositionOnUpdate={false} open={open} onRequestClose={this.handleRequestClose} > {open && <EventListener elementName="window" onKeyUp={this.handleKeyUp} /> } {open && <Clock ref="clock" format={format} initialTime={initialTime} onChangeMinutes={onClockChangeMinutes} /> } </Dialog> ); } } export default TimePickerDialog;
jekyll-admin/src/containers/views/tests/pageedit.spec.js
mparlak/mparlak.github.io
import React from 'react'; import { shallow } from 'enzyme'; import { PageEdit } from '../PageEdit'; import Errors from '../../../components/Errors'; import Button from '../../../components/Button'; import { config, page } from './fixtures'; const defaultProps = { page: page, errors: [], fieldChanged: false, updated: false, isFetching: false, router: {}, route: {}, config: config, params: { splat: [null, "page", "md"] } }; const setup = (props = defaultProps) => { const actions = { fetchPage: jest.fn(), putPage: jest.fn(), deletePage: jest.fn(), updateTitle: jest.fn(), updateBody: jest.fn(), updatePath: jest.fn(), updateDraft: jest.fn(), clearErrors: jest.fn() }; const component = shallow(<PageEdit {...actions} {...props} />); return { component, actions, saveButton: component.find(Button).first(), deleteButton: component.find(Button).last(), errors: component.find(Errors), props }; }; describe('Containers::PageEdit', () => { it('should render correctly', () => { let { component } = setup(Object.assign( {}, defaultProps, { isFetching: true } )); component = setup(Object.assign( {}, defaultProps, { page: {} } )).component; expect(component.find('h1').node).toBeTruthy(); }); it('should not render error messages initially', () => { const { errors } = setup(); expect(errors.node).toBeFalsy(); }); it('should render error messages', () => { const { errors } = setup(Object.assign({}, defaultProps, { errors: ['The title field is required!'] })); expect(errors.node).toBeTruthy(); }); it('should not call putPage if a field is not changed.', () => { const { saveButton, actions } = setup(); saveButton.simulate('click'); expect(actions.putPage).not.toHaveBeenCalled(); }); it('should call putPage if a field is changed.', () => { const { saveButton, actions } = setup(Object.assign({}, defaultProps, { fieldChanged: true })); saveButton.simulate('click'); expect(actions.putPage).toHaveBeenCalled(); }); it('should call deletePage', () => { const { deleteButton, actions } = setup(); deleteButton.simulate('click'); expect(actions.deletePage).not.toHaveBeenCalled(); // TODO pass prompt }); });
server/sonar-web/src/main/js/apps/overview/components/events-list-filter.js
vamsirajendra/sonarqube
import React from 'react'; import Select from 'react-select'; const TYPES = ['All', 'Version', 'Alert', 'Profile', 'Other']; export const EventsListFilter = React.createClass({ propTypes: { onFilter: React.PropTypes.func.isRequired, currentFilter: React.PropTypes.string.isRequired }, handleChange(selected) { this.props.onFilter(selected.value); }, render () { const options = TYPES.map(type => { return { value: type, label: window.t('event.category', type) }; }); return <Select value={this.props.currentFilter} options={options} clearable={false} searchable={false} onChange={this.handleChange} style={{ width: '125px' }}/>; } });